babylon.max.js 3.9 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738
  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. //# sourceMappingURL=babylon.types.js.map
  18. var BABYLON;
  19. (function (BABYLON) {
  20. var KeyboardEventTypes = /** @class */ (function () {
  21. function KeyboardEventTypes() {
  22. }
  23. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  24. get: function () {
  25. return KeyboardEventTypes._KEYDOWN;
  26. },
  27. enumerable: true,
  28. configurable: true
  29. });
  30. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  31. get: function () {
  32. return KeyboardEventTypes._KEYUP;
  33. },
  34. enumerable: true,
  35. configurable: true
  36. });
  37. KeyboardEventTypes._KEYDOWN = 0x01;
  38. KeyboardEventTypes._KEYUP = 0x02;
  39. return KeyboardEventTypes;
  40. }());
  41. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  42. var KeyboardInfo = /** @class */ (function () {
  43. function KeyboardInfo(type, event) {
  44. this.type = type;
  45. this.event = event;
  46. }
  47. return KeyboardInfo;
  48. }());
  49. BABYLON.KeyboardInfo = KeyboardInfo;
  50. /**
  51. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  52. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  53. */
  54. var KeyboardInfoPre = /** @class */ (function (_super) {
  55. __extends(KeyboardInfoPre, _super);
  56. function KeyboardInfoPre(type, event) {
  57. var _this = _super.call(this, type, event) || this;
  58. _this.skipOnPointerObservable = false;
  59. return _this;
  60. }
  61. return KeyboardInfoPre;
  62. }(KeyboardInfo));
  63. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  64. })(BABYLON || (BABYLON = {}));
  65. //# sourceMappingURL=babylon.keyboardEvents.js.map
  66. var BABYLON;
  67. (function (BABYLON) {
  68. var PointerEventTypes = /** @class */ (function () {
  69. function PointerEventTypes() {
  70. }
  71. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  72. get: function () {
  73. return PointerEventTypes._POINTERDOWN;
  74. },
  75. enumerable: true,
  76. configurable: true
  77. });
  78. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  79. get: function () {
  80. return PointerEventTypes._POINTERUP;
  81. },
  82. enumerable: true,
  83. configurable: true
  84. });
  85. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  86. get: function () {
  87. return PointerEventTypes._POINTERMOVE;
  88. },
  89. enumerable: true,
  90. configurable: true
  91. });
  92. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  93. get: function () {
  94. return PointerEventTypes._POINTERWHEEL;
  95. },
  96. enumerable: true,
  97. configurable: true
  98. });
  99. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  100. get: function () {
  101. return PointerEventTypes._POINTERPICK;
  102. },
  103. enumerable: true,
  104. configurable: true
  105. });
  106. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  107. get: function () {
  108. return PointerEventTypes._POINTERTAP;
  109. },
  110. enumerable: true,
  111. configurable: true
  112. });
  113. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  114. get: function () {
  115. return PointerEventTypes._POINTERDOUBLETAP;
  116. },
  117. enumerable: true,
  118. configurable: true
  119. });
  120. PointerEventTypes._POINTERDOWN = 0x01;
  121. PointerEventTypes._POINTERUP = 0x02;
  122. PointerEventTypes._POINTERMOVE = 0x04;
  123. PointerEventTypes._POINTERWHEEL = 0x08;
  124. PointerEventTypes._POINTERPICK = 0x10;
  125. PointerEventTypes._POINTERTAP = 0x20;
  126. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  127. return PointerEventTypes;
  128. }());
  129. BABYLON.PointerEventTypes = PointerEventTypes;
  130. var PointerInfoBase = /** @class */ (function () {
  131. function PointerInfoBase(type, event) {
  132. this.type = type;
  133. this.event = event;
  134. }
  135. return PointerInfoBase;
  136. }());
  137. BABYLON.PointerInfoBase = PointerInfoBase;
  138. /**
  139. * This class is used to store pointer related info for the onPrePointerObservable event.
  140. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  141. */
  142. var PointerInfoPre = /** @class */ (function (_super) {
  143. __extends(PointerInfoPre, _super);
  144. function PointerInfoPre(type, event, localX, localY) {
  145. var _this = _super.call(this, type, event) || this;
  146. _this.skipOnPointerObservable = false;
  147. _this.localPosition = new BABYLON.Vector2(localX, localY);
  148. return _this;
  149. }
  150. return PointerInfoPre;
  151. }(PointerInfoBase));
  152. BABYLON.PointerInfoPre = PointerInfoPre;
  153. /**
  154. * This type contains all the data related to a pointer event in Babylon.js.
  155. * 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.
  156. */
  157. var PointerInfo = /** @class */ (function (_super) {
  158. __extends(PointerInfo, _super);
  159. function PointerInfo(type, event, pickInfo) {
  160. var _this = _super.call(this, type, event) || this;
  161. _this.pickInfo = pickInfo;
  162. return _this;
  163. }
  164. return PointerInfo;
  165. }(PointerInfoBase));
  166. BABYLON.PointerInfo = PointerInfo;
  167. })(BABYLON || (BABYLON = {}));
  168. //# sourceMappingURL=babylon.pointerEvents.js.map
  169. var BABYLON;
  170. (function (BABYLON) {
  171. BABYLON.ToGammaSpace = 1 / 2.2;
  172. BABYLON.ToLinearSpace = 2.2;
  173. BABYLON.Epsilon = 0.001;
  174. var Color3 = /** @class */ (function () {
  175. /**
  176. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  177. */
  178. function Color3(r, g, b) {
  179. if (r === void 0) { r = 0; }
  180. if (g === void 0) { g = 0; }
  181. if (b === void 0) { b = 0; }
  182. this.r = r;
  183. this.g = g;
  184. this.b = b;
  185. }
  186. /**
  187. * Returns a string with the Color3 current values.
  188. */
  189. Color3.prototype.toString = function () {
  190. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  191. };
  192. /**
  193. * Returns the string "Color3".
  194. */
  195. Color3.prototype.getClassName = function () {
  196. return "Color3";
  197. };
  198. /**
  199. * Returns the Color3 hash code.
  200. */
  201. Color3.prototype.getHashCode = function () {
  202. var hash = this.r || 0;
  203. hash = (hash * 397) ^ (this.g || 0);
  204. hash = (hash * 397) ^ (this.b || 0);
  205. return hash;
  206. };
  207. // Operators
  208. /**
  209. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  210. * Returns the Color3.
  211. */
  212. Color3.prototype.toArray = function (array, index) {
  213. if (index === undefined) {
  214. index = 0;
  215. }
  216. array[index] = this.r;
  217. array[index + 1] = this.g;
  218. array[index + 2] = this.b;
  219. return this;
  220. };
  221. /**
  222. * Returns a new Color4 object from the current Color3 and the passed alpha.
  223. */
  224. Color3.prototype.toColor4 = function (alpha) {
  225. if (alpha === void 0) { alpha = 1; }
  226. return new Color4(this.r, this.g, this.b, alpha);
  227. };
  228. /**
  229. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  230. */
  231. Color3.prototype.asArray = function () {
  232. var result = new Array();
  233. this.toArray(result, 0);
  234. return result;
  235. };
  236. /**
  237. * Returns the luminance value (float).
  238. */
  239. Color3.prototype.toLuminance = function () {
  240. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  241. };
  242. /**
  243. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  244. * Returns this new object.
  245. */
  246. Color3.prototype.multiply = function (otherColor) {
  247. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  248. };
  249. /**
  250. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  251. * Returns the current Color3.
  252. */
  253. Color3.prototype.multiplyToRef = function (otherColor, result) {
  254. result.r = this.r * otherColor.r;
  255. result.g = this.g * otherColor.g;
  256. result.b = this.b * otherColor.b;
  257. return this;
  258. };
  259. /**
  260. * Boolean : True if the rgb values are equal to the passed ones.
  261. */
  262. Color3.prototype.equals = function (otherColor) {
  263. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  264. };
  265. /**
  266. * Boolean : True if the rgb values are equal to the passed ones.
  267. */
  268. Color3.prototype.equalsFloats = function (r, g, b) {
  269. return this.r === r && this.g === g && this.b === b;
  270. };
  271. /**
  272. * Multiplies in place each rgb value by scale.
  273. * Returns the updated Color3.
  274. */
  275. Color3.prototype.scale = function (scale) {
  276. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  277. };
  278. /**
  279. * Multiplies the rgb values by scale and stores the result into "result".
  280. * Returns the unmodified current Color3.
  281. */
  282. Color3.prototype.scaleToRef = function (scale, result) {
  283. result.r = this.r * scale;
  284. result.g = this.g * scale;
  285. result.b = this.b * scale;
  286. return this;
  287. };
  288. /**
  289. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  290. */
  291. Color3.prototype.add = function (otherColor) {
  292. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  293. };
  294. /**
  295. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  296. * Returns the unmodified current Color3.
  297. */
  298. Color3.prototype.addToRef = function (otherColor, result) {
  299. result.r = this.r + otherColor.r;
  300. result.g = this.g + otherColor.g;
  301. result.b = this.b + otherColor.b;
  302. return this;
  303. };
  304. /**
  305. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  306. */
  307. Color3.prototype.subtract = function (otherColor) {
  308. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  309. };
  310. /**
  311. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  312. * Returns the unmodified current Color3.
  313. */
  314. Color3.prototype.subtractToRef = function (otherColor, result) {
  315. result.r = this.r - otherColor.r;
  316. result.g = this.g - otherColor.g;
  317. result.b = this.b - otherColor.b;
  318. return this;
  319. };
  320. /**
  321. * Returns a new Color3 copied the current one.
  322. */
  323. Color3.prototype.clone = function () {
  324. return new Color3(this.r, this.g, this.b);
  325. };
  326. /**
  327. * Copies the rgb values from the source in the current Color3.
  328. * Returns the updated Color3.
  329. */
  330. Color3.prototype.copyFrom = function (source) {
  331. this.r = source.r;
  332. this.g = source.g;
  333. this.b = source.b;
  334. return this;
  335. };
  336. /**
  337. * Updates the Color3 rgb values from the passed floats.
  338. * Returns the Color3.
  339. */
  340. Color3.prototype.copyFromFloats = function (r, g, b) {
  341. this.r = r;
  342. this.g = g;
  343. this.b = b;
  344. return this;
  345. };
  346. /**
  347. * Updates the Color3 rgb values from the passed floats.
  348. * Returns the Color3.
  349. */
  350. Color3.prototype.set = function (r, g, b) {
  351. return this.copyFromFloats(r, g, b);
  352. };
  353. /**
  354. * Returns the Color3 hexadecimal code as a string.
  355. */
  356. Color3.prototype.toHexString = function () {
  357. var intR = (this.r * 255) | 0;
  358. var intG = (this.g * 255) | 0;
  359. var intB = (this.b * 255) | 0;
  360. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  361. };
  362. /**
  363. * Returns a new Color3 converted to linear space.
  364. */
  365. Color3.prototype.toLinearSpace = function () {
  366. var convertedColor = new Color3();
  367. this.toLinearSpaceToRef(convertedColor);
  368. return convertedColor;
  369. };
  370. /**
  371. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  372. * Returns the unmodified Color3.
  373. */
  374. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  375. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  376. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  377. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  378. return this;
  379. };
  380. /**
  381. * Returns a new Color3 converted to gamma space.
  382. */
  383. Color3.prototype.toGammaSpace = function () {
  384. var convertedColor = new Color3();
  385. this.toGammaSpaceToRef(convertedColor);
  386. return convertedColor;
  387. };
  388. /**
  389. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  390. * Returns the unmodified Color3.
  391. */
  392. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  393. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  394. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  395. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  396. return this;
  397. };
  398. // Statics
  399. /**
  400. * Creates a new Color3 from the string containing valid hexadecimal values.
  401. */
  402. Color3.FromHexString = function (hex) {
  403. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  404. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  405. return new Color3(0, 0, 0);
  406. }
  407. var r = parseInt(hex.substring(1, 3), 16);
  408. var g = parseInt(hex.substring(3, 5), 16);
  409. var b = parseInt(hex.substring(5, 7), 16);
  410. return Color3.FromInts(r, g, b);
  411. };
  412. /**
  413. * Creates a new Vector3 from the startind index of the passed array.
  414. */
  415. Color3.FromArray = function (array, offset) {
  416. if (offset === void 0) { offset = 0; }
  417. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  418. };
  419. /**
  420. * Creates a new Color3 from integer values ( < 256).
  421. */
  422. Color3.FromInts = function (r, g, b) {
  423. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  424. };
  425. /**
  426. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  427. */
  428. Color3.Lerp = function (start, end, amount) {
  429. var r = start.r + ((end.r - start.r) * amount);
  430. var g = start.g + ((end.g - start.g) * amount);
  431. var b = start.b + ((end.b - start.b) * amount);
  432. return new Color3(r, g, b);
  433. };
  434. Color3.Red = function () { return new Color3(1, 0, 0); };
  435. Color3.Green = function () { return new Color3(0, 1, 0); };
  436. Color3.Blue = function () { return new Color3(0, 0, 1); };
  437. Color3.Black = function () { return new Color3(0, 0, 0); };
  438. Color3.White = function () { return new Color3(1, 1, 1); };
  439. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  440. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  441. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  442. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  443. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  444. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  445. return Color3;
  446. }());
  447. BABYLON.Color3 = Color3;
  448. var Color4 = /** @class */ (function () {
  449. /**
  450. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  451. */
  452. function Color4(r, g, b, a) {
  453. if (r === void 0) { r = 0; }
  454. if (g === void 0) { g = 0; }
  455. if (b === void 0) { b = 0; }
  456. if (a === void 0) { a = 1; }
  457. this.r = r;
  458. this.g = g;
  459. this.b = b;
  460. this.a = a;
  461. }
  462. // Operators
  463. /**
  464. * Adds in place the passed Color4 values to the current Color4.
  465. * Returns the updated Color4.
  466. */
  467. Color4.prototype.addInPlace = function (right) {
  468. this.r += right.r;
  469. this.g += right.g;
  470. this.b += right.b;
  471. this.a += right.a;
  472. return this;
  473. };
  474. /**
  475. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  476. */
  477. Color4.prototype.asArray = function () {
  478. var result = new Array();
  479. this.toArray(result, 0);
  480. return result;
  481. };
  482. /**
  483. * Stores from the starting index in the passed array the Color4 successive values.
  484. * Returns the Color4.
  485. */
  486. Color4.prototype.toArray = function (array, index) {
  487. if (index === undefined) {
  488. index = 0;
  489. }
  490. array[index] = this.r;
  491. array[index + 1] = this.g;
  492. array[index + 2] = this.b;
  493. array[index + 3] = this.a;
  494. return this;
  495. };
  496. /**
  497. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  498. */
  499. Color4.prototype.add = function (right) {
  500. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  501. };
  502. /**
  503. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  504. */
  505. Color4.prototype.subtract = function (right) {
  506. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  507. };
  508. /**
  509. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  510. * Returns the Color4.
  511. */
  512. Color4.prototype.subtractToRef = function (right, result) {
  513. result.r = this.r - right.r;
  514. result.g = this.g - right.g;
  515. result.b = this.b - right.b;
  516. result.a = this.a - right.a;
  517. return this;
  518. };
  519. /**
  520. * Creates a new Color4 with the current Color4 values multiplied by scale.
  521. */
  522. Color4.prototype.scale = function (scale) {
  523. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  524. };
  525. /**
  526. * Multiplies the current Color4 values by scale and stores the result in "result".
  527. * Returns the Color4.
  528. */
  529. Color4.prototype.scaleToRef = function (scale, result) {
  530. result.r = this.r * scale;
  531. result.g = this.g * scale;
  532. result.b = this.b * scale;
  533. result.a = this.a * scale;
  534. return this;
  535. };
  536. /**
  537. * Multipy an RGBA Color4 value by another and return a new Color4 object
  538. * @param color The Color4 (RGBA) value to multiply by
  539. * @returns A new Color4.
  540. */
  541. Color4.prototype.multiply = function (color) {
  542. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  543. };
  544. /**
  545. * Multipy an RGBA Color4 value by another and push the result in a reference value
  546. * @param color The Color4 (RGBA) value to multiply by
  547. * @param result The Color4 (RGBA) to fill the result in
  548. * @returns the result Color4.
  549. */
  550. Color4.prototype.multiplyToRef = function (color, result) {
  551. result.r = this.r * color.r;
  552. result.g = this.g * color.g;
  553. result.b = this.b * color.b;
  554. result.a = this.a * color.a;
  555. return result;
  556. };
  557. /**
  558. * Returns a string with the Color4 values.
  559. */
  560. Color4.prototype.toString = function () {
  561. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  562. };
  563. /**
  564. * Returns the string "Color4"
  565. */
  566. Color4.prototype.getClassName = function () {
  567. return "Color4";
  568. };
  569. /**
  570. * Return the Color4 hash code as a number.
  571. */
  572. Color4.prototype.getHashCode = function () {
  573. var hash = this.r || 0;
  574. hash = (hash * 397) ^ (this.g || 0);
  575. hash = (hash * 397) ^ (this.b || 0);
  576. hash = (hash * 397) ^ (this.a || 0);
  577. return hash;
  578. };
  579. /**
  580. * Creates a new Color4 copied from the current one.
  581. */
  582. Color4.prototype.clone = function () {
  583. return new Color4(this.r, this.g, this.b, this.a);
  584. };
  585. /**
  586. * Copies the passed Color4 values into the current one.
  587. * Returns the updated Color4.
  588. */
  589. Color4.prototype.copyFrom = function (source) {
  590. this.r = source.r;
  591. this.g = source.g;
  592. this.b = source.b;
  593. this.a = source.a;
  594. return this;
  595. };
  596. /**
  597. * Copies the passed float values into the current one.
  598. * Returns the updated Color4.
  599. */
  600. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  601. this.r = r;
  602. this.g = g;
  603. this.b = b;
  604. this.a = a;
  605. return this;
  606. };
  607. /**
  608. * Copies the passed float values into the current one.
  609. * Returns the updated Color4.
  610. */
  611. Color4.prototype.set = function (r, g, b, a) {
  612. return this.copyFromFloats(r, g, b, a);
  613. };
  614. /**
  615. * Returns a string containing the hexadecimal Color4 code.
  616. */
  617. Color4.prototype.toHexString = function () {
  618. var intR = (this.r * 255) | 0;
  619. var intG = (this.g * 255) | 0;
  620. var intB = (this.b * 255) | 0;
  621. var intA = (this.a * 255) | 0;
  622. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  623. };
  624. /**
  625. * Returns a new Color4 converted to linear space.
  626. */
  627. Color4.prototype.toLinearSpace = function () {
  628. var convertedColor = new Color4();
  629. this.toLinearSpaceToRef(convertedColor);
  630. return convertedColor;
  631. };
  632. /**
  633. * Converts the Color4 values to linear space and stores the result in "convertedColor".
  634. * Returns the unmodified Color4.
  635. */
  636. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  637. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  638. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  639. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  640. convertedColor.a = this.a;
  641. return this;
  642. };
  643. /**
  644. * Returns a new Color4 converted to gamma space.
  645. */
  646. Color4.prototype.toGammaSpace = function () {
  647. var convertedColor = new Color4();
  648. this.toGammaSpaceToRef(convertedColor);
  649. return convertedColor;
  650. };
  651. /**
  652. * Converts the Color4 values to gamma space and stores the result in "convertedColor".
  653. * Returns the unmodified Color4.
  654. */
  655. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  656. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  657. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  658. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  659. convertedColor.a = this.a;
  660. return this;
  661. };
  662. // Statics
  663. /**
  664. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  665. */
  666. Color4.FromHexString = function (hex) {
  667. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  668. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  669. return new Color4(0.0, 0.0, 0.0, 0.0);
  670. }
  671. var r = parseInt(hex.substring(1, 3), 16);
  672. var g = parseInt(hex.substring(3, 5), 16);
  673. var b = parseInt(hex.substring(5, 7), 16);
  674. var a = parseInt(hex.substring(7, 9), 16);
  675. return Color4.FromInts(r, g, b, a);
  676. };
  677. /**
  678. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  679. */
  680. Color4.Lerp = function (left, right, amount) {
  681. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  682. Color4.LerpToRef(left, right, amount, result);
  683. return result;
  684. };
  685. /**
  686. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  687. */
  688. Color4.LerpToRef = function (left, right, amount, result) {
  689. result.r = left.r + (right.r - left.r) * amount;
  690. result.g = left.g + (right.g - left.g) * amount;
  691. result.b = left.b + (right.b - left.b) * amount;
  692. result.a = left.a + (right.a - left.a) * amount;
  693. };
  694. /**
  695. * Creates a new Color4 from the starting index element of the passed array.
  696. */
  697. Color4.FromArray = function (array, offset) {
  698. if (offset === void 0) { offset = 0; }
  699. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  700. };
  701. /**
  702. * Creates a new Color4 from the passed integers ( < 256 ).
  703. */
  704. Color4.FromInts = function (r, g, b, a) {
  705. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  706. };
  707. Color4.CheckColors4 = function (colors, count) {
  708. // Check if color3 was used
  709. if (colors.length === count * 3) {
  710. var colors4 = [];
  711. for (var index = 0; index < colors.length; index += 3) {
  712. var newIndex = (index / 3) * 4;
  713. colors4[newIndex] = colors[index];
  714. colors4[newIndex + 1] = colors[index + 1];
  715. colors4[newIndex + 2] = colors[index + 2];
  716. colors4[newIndex + 3] = 1.0;
  717. }
  718. return colors4;
  719. }
  720. return colors;
  721. };
  722. return Color4;
  723. }());
  724. BABYLON.Color4 = Color4;
  725. var Vector2 = /** @class */ (function () {
  726. /**
  727. * Creates a new Vector2 from the passed x and y coordinates.
  728. */
  729. function Vector2(x, y) {
  730. this.x = x;
  731. this.y = y;
  732. }
  733. /**
  734. * Returns a string with the Vector2 coordinates.
  735. */
  736. Vector2.prototype.toString = function () {
  737. return "{X: " + this.x + " Y:" + this.y + "}";
  738. };
  739. /**
  740. * Returns the string "Vector2"
  741. */
  742. Vector2.prototype.getClassName = function () {
  743. return "Vector2";
  744. };
  745. /**
  746. * Returns the Vector2 hash code as a number.
  747. */
  748. Vector2.prototype.getHashCode = function () {
  749. var hash = this.x || 0;
  750. hash = (hash * 397) ^ (this.y || 0);
  751. return hash;
  752. };
  753. // Operators
  754. /**
  755. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  756. * Returns the Vector2.
  757. */
  758. Vector2.prototype.toArray = function (array, index) {
  759. if (index === void 0) { index = 0; }
  760. array[index] = this.x;
  761. array[index + 1] = this.y;
  762. return this;
  763. };
  764. /**
  765. * Returns a new array with 2 elements : the Vector2 coordinates.
  766. */
  767. Vector2.prototype.asArray = function () {
  768. var result = new Array();
  769. this.toArray(result, 0);
  770. return result;
  771. };
  772. /**
  773. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  774. * Returns the updated Vector2.
  775. */
  776. Vector2.prototype.copyFrom = function (source) {
  777. this.x = source.x;
  778. this.y = source.y;
  779. return this;
  780. };
  781. /**
  782. * Sets the Vector2 coordinates with the passed floats.
  783. * Returns the updated Vector2.
  784. */
  785. Vector2.prototype.copyFromFloats = function (x, y) {
  786. this.x = x;
  787. this.y = y;
  788. return this;
  789. };
  790. /**
  791. * Sets the Vector2 coordinates with the passed floats.
  792. * Returns the updated Vector2.
  793. */
  794. Vector2.prototype.set = function (x, y) {
  795. return this.copyFromFloats(x, y);
  796. };
  797. /**
  798. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  799. */
  800. Vector2.prototype.add = function (otherVector) {
  801. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  802. };
  803. /**
  804. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  805. * Returns the Vector2.
  806. */
  807. Vector2.prototype.addToRef = function (otherVector, result) {
  808. result.x = this.x + otherVector.x;
  809. result.y = this.y + otherVector.y;
  810. return this;
  811. };
  812. /**
  813. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  814. * Returns the updated Vector2.
  815. */
  816. Vector2.prototype.addInPlace = function (otherVector) {
  817. this.x += otherVector.x;
  818. this.y += otherVector.y;
  819. return this;
  820. };
  821. /**
  822. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  823. */
  824. Vector2.prototype.addVector3 = function (otherVector) {
  825. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  826. };
  827. /**
  828. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  829. */
  830. Vector2.prototype.subtract = function (otherVector) {
  831. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  832. };
  833. /**
  834. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  835. * Returns the Vector2.
  836. */
  837. Vector2.prototype.subtractToRef = function (otherVector, result) {
  838. result.x = this.x - otherVector.x;
  839. result.y = this.y - otherVector.y;
  840. return this;
  841. };
  842. /**
  843. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  844. * Returns the updated Vector2.
  845. */
  846. Vector2.prototype.subtractInPlace = function (otherVector) {
  847. this.x -= otherVector.x;
  848. this.y -= otherVector.y;
  849. return this;
  850. };
  851. /**
  852. * Multiplies in place the current Vector2 coordinates by the passed ones.
  853. * Returns the updated Vector2.
  854. */
  855. Vector2.prototype.multiplyInPlace = function (otherVector) {
  856. this.x *= otherVector.x;
  857. this.y *= otherVector.y;
  858. return this;
  859. };
  860. /**
  861. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  862. */
  863. Vector2.prototype.multiply = function (otherVector) {
  864. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  865. };
  866. /**
  867. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  868. * Returns the Vector2.
  869. */
  870. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  871. result.x = this.x * otherVector.x;
  872. result.y = this.y * otherVector.y;
  873. return this;
  874. };
  875. /**
  876. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  877. */
  878. Vector2.prototype.multiplyByFloats = function (x, y) {
  879. return new Vector2(this.x * x, this.y * y);
  880. };
  881. /**
  882. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  883. */
  884. Vector2.prototype.divide = function (otherVector) {
  885. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  886. };
  887. /**
  888. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  889. * Returns the Vector2.
  890. */
  891. Vector2.prototype.divideToRef = function (otherVector, result) {
  892. result.x = this.x / otherVector.x;
  893. result.y = this.y / otherVector.y;
  894. return this;
  895. };
  896. /**
  897. * Returns a new Vector2 with current Vector2 negated coordinates.
  898. */
  899. Vector2.prototype.negate = function () {
  900. return new Vector2(-this.x, -this.y);
  901. };
  902. /**
  903. * Multiply the Vector2 coordinates by scale.
  904. * Returns the updated Vector2.
  905. */
  906. Vector2.prototype.scaleInPlace = function (scale) {
  907. this.x *= scale;
  908. this.y *= scale;
  909. return this;
  910. };
  911. /**
  912. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  913. */
  914. Vector2.prototype.scale = function (scale) {
  915. return new Vector2(this.x * scale, this.y * scale);
  916. };
  917. /**
  918. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  919. */
  920. Vector2.prototype.equals = function (otherVector) {
  921. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  922. };
  923. /**
  924. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  925. */
  926. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  927. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  928. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  929. };
  930. // Properties
  931. /**
  932. * Returns the vector length (float).
  933. */
  934. Vector2.prototype.length = function () {
  935. return Math.sqrt(this.x * this.x + this.y * this.y);
  936. };
  937. /**
  938. * Returns the vector squared length (float);
  939. */
  940. Vector2.prototype.lengthSquared = function () {
  941. return (this.x * this.x + this.y * this.y);
  942. };
  943. // Methods
  944. /**
  945. * Normalize the vector.
  946. * Returns the updated Vector2.
  947. */
  948. Vector2.prototype.normalize = function () {
  949. var len = this.length();
  950. if (len === 0)
  951. return this;
  952. var num = 1.0 / len;
  953. this.x *= num;
  954. this.y *= num;
  955. return this;
  956. };
  957. /**
  958. * Returns a new Vector2 copied from the Vector2.
  959. */
  960. Vector2.prototype.clone = function () {
  961. return new Vector2(this.x, this.y);
  962. };
  963. // Statics
  964. /**
  965. * Returns a new Vector2(0, 0)
  966. */
  967. Vector2.Zero = function () {
  968. return new Vector2(0, 0);
  969. };
  970. /**
  971. * Returns a new Vector2(1, 1)
  972. */
  973. Vector2.One = function () {
  974. return new Vector2(1, 1);
  975. };
  976. /**
  977. * Returns a new Vector2 set from the passed index element of the passed array.
  978. */
  979. Vector2.FromArray = function (array, offset) {
  980. if (offset === void 0) { offset = 0; }
  981. return new Vector2(array[offset], array[offset + 1]);
  982. };
  983. /**
  984. * Sets "result" from the passed index element of the passed array.
  985. */
  986. Vector2.FromArrayToRef = function (array, offset, result) {
  987. result.x = array[offset];
  988. result.y = array[offset + 1];
  989. };
  990. /**
  991. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  992. */
  993. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  994. var squared = amount * amount;
  995. var cubed = amount * squared;
  996. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  997. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  998. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  999. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1000. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1001. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1002. return new Vector2(x, y);
  1003. };
  1004. /**
  1005. * 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".
  1006. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  1007. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  1008. */
  1009. Vector2.Clamp = function (value, min, max) {
  1010. var x = value.x;
  1011. x = (x > max.x) ? max.x : x;
  1012. x = (x < min.x) ? min.x : x;
  1013. var y = value.y;
  1014. y = (y > max.y) ? max.y : y;
  1015. y = (y < min.y) ? min.y : y;
  1016. return new Vector2(x, y);
  1017. };
  1018. /**
  1019. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  1020. */
  1021. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1022. var squared = amount * amount;
  1023. var cubed = amount * squared;
  1024. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1025. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1026. var part3 = (cubed - (2.0 * squared)) + amount;
  1027. var part4 = cubed - squared;
  1028. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1029. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1030. return new Vector2(x, y);
  1031. };
  1032. /**
  1033. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  1034. */
  1035. Vector2.Lerp = function (start, end, amount) {
  1036. var x = start.x + ((end.x - start.x) * amount);
  1037. var y = start.y + ((end.y - start.y) * amount);
  1038. return new Vector2(x, y);
  1039. };
  1040. /**
  1041. * Returns the dot product (float) of the vector "left" and the vector "right".
  1042. */
  1043. Vector2.Dot = function (left, right) {
  1044. return left.x * right.x + left.y * right.y;
  1045. };
  1046. /**
  1047. * Returns a new Vector2 equal to the normalized passed vector.
  1048. */
  1049. Vector2.Normalize = function (vector) {
  1050. var newVector = vector.clone();
  1051. newVector.normalize();
  1052. return newVector;
  1053. };
  1054. /**
  1055. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  1056. */
  1057. Vector2.Minimize = function (left, right) {
  1058. var x = (left.x < right.x) ? left.x : right.x;
  1059. var y = (left.y < right.y) ? left.y : right.y;
  1060. return new Vector2(x, y);
  1061. };
  1062. /**
  1063. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  1064. */
  1065. Vector2.Maximize = function (left, right) {
  1066. var x = (left.x > right.x) ? left.x : right.x;
  1067. var y = (left.y > right.y) ? left.y : right.y;
  1068. return new Vector2(x, y);
  1069. };
  1070. /**
  1071. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  1072. */
  1073. Vector2.Transform = function (vector, transformation) {
  1074. var r = Vector2.Zero();
  1075. Vector2.TransformToRef(vector, transformation, r);
  1076. return r;
  1077. };
  1078. /**
  1079. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  1080. */
  1081. Vector2.TransformToRef = function (vector, transformation, result) {
  1082. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  1083. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  1084. result.x = x;
  1085. result.y = y;
  1086. };
  1087. /**
  1088. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  1089. */
  1090. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  1091. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  1092. var sign = a < 0 ? -1 : 1;
  1093. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  1094. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  1095. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  1096. };
  1097. /**
  1098. * Returns the distance (float) between the vectors "value1" and "value2".
  1099. */
  1100. Vector2.Distance = function (value1, value2) {
  1101. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  1102. };
  1103. /**
  1104. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1105. */
  1106. Vector2.DistanceSquared = function (value1, value2) {
  1107. var x = value1.x - value2.x;
  1108. var y = value1.y - value2.y;
  1109. return (x * x) + (y * y);
  1110. };
  1111. /**
  1112. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  1113. */
  1114. Vector2.Center = function (value1, value2) {
  1115. var center = value1.add(value2);
  1116. center.scaleInPlace(0.5);
  1117. return center;
  1118. };
  1119. /**
  1120. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  1121. */
  1122. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  1123. var l2 = Vector2.DistanceSquared(segA, segB);
  1124. if (l2 === 0.0) {
  1125. return Vector2.Distance(p, segA);
  1126. }
  1127. var v = segB.subtract(segA);
  1128. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  1129. var proj = segA.add(v.multiplyByFloats(t, t));
  1130. return Vector2.Distance(p, proj);
  1131. };
  1132. return Vector2;
  1133. }());
  1134. BABYLON.Vector2 = Vector2;
  1135. var Vector3 = /** @class */ (function () {
  1136. /**
  1137. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1138. * A Vector3 is the main object used in 3D geometry.
  1139. * It can represent etiher the coordinates of a point the space, either a direction.
  1140. */
  1141. function Vector3(x, y, z) {
  1142. this.x = x;
  1143. this.y = y;
  1144. this.z = z;
  1145. }
  1146. /**
  1147. * Returns a string with the Vector3 coordinates.
  1148. */
  1149. Vector3.prototype.toString = function () {
  1150. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1151. };
  1152. /**
  1153. * Returns the string "Vector3"
  1154. */
  1155. Vector3.prototype.getClassName = function () {
  1156. return "Vector3";
  1157. };
  1158. /**
  1159. * Returns the Vector hash code.
  1160. */
  1161. Vector3.prototype.getHashCode = function () {
  1162. var hash = this.x || 0;
  1163. hash = (hash * 397) ^ (this.y || 0);
  1164. hash = (hash * 397) ^ (this.z || 0);
  1165. return hash;
  1166. };
  1167. // Operators
  1168. /**
  1169. * Returns a new array with three elements : the coordinates the Vector3.
  1170. */
  1171. Vector3.prototype.asArray = function () {
  1172. var result = [];
  1173. this.toArray(result, 0);
  1174. return result;
  1175. };
  1176. /**
  1177. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1178. * Returns the Vector3.
  1179. */
  1180. Vector3.prototype.toArray = function (array, index) {
  1181. if (index === void 0) { index = 0; }
  1182. array[index] = this.x;
  1183. array[index + 1] = this.y;
  1184. array[index + 2] = this.z;
  1185. return this;
  1186. };
  1187. /**
  1188. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1189. */
  1190. Vector3.prototype.toQuaternion = function () {
  1191. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1192. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1193. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1194. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1195. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1196. var cosy = Math.cos(this.y * 0.5);
  1197. var siny = Math.sin(this.y * 0.5);
  1198. result.x = coszMinusx * siny;
  1199. result.y = -sinzMinusx * siny;
  1200. result.z = sinxPlusz * cosy;
  1201. result.w = cosxPlusz * cosy;
  1202. return result;
  1203. };
  1204. /**
  1205. * Adds the passed vector to the current Vector3.
  1206. * Returns the updated Vector3.
  1207. */
  1208. Vector3.prototype.addInPlace = function (otherVector) {
  1209. this.x += otherVector.x;
  1210. this.y += otherVector.y;
  1211. this.z += otherVector.z;
  1212. return this;
  1213. };
  1214. /**
  1215. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1216. */
  1217. Vector3.prototype.add = function (otherVector) {
  1218. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1219. };
  1220. /**
  1221. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1222. * Returns the current Vector3.
  1223. */
  1224. Vector3.prototype.addToRef = function (otherVector, result) {
  1225. result.x = this.x + otherVector.x;
  1226. result.y = this.y + otherVector.y;
  1227. result.z = this.z + otherVector.z;
  1228. return this;
  1229. };
  1230. /**
  1231. * Subtract the passed vector from the current Vector3.
  1232. * Returns the updated Vector3.
  1233. */
  1234. Vector3.prototype.subtractInPlace = function (otherVector) {
  1235. this.x -= otherVector.x;
  1236. this.y -= otherVector.y;
  1237. this.z -= otherVector.z;
  1238. return this;
  1239. };
  1240. /**
  1241. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1242. */
  1243. Vector3.prototype.subtract = function (otherVector) {
  1244. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1245. };
  1246. /**
  1247. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1248. * Returns the current Vector3.
  1249. */
  1250. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1251. result.x = this.x - otherVector.x;
  1252. result.y = this.y - otherVector.y;
  1253. result.z = this.z - otherVector.z;
  1254. return this;
  1255. };
  1256. /**
  1257. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1258. */
  1259. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1260. return new Vector3(this.x - x, this.y - y, this.z - z);
  1261. };
  1262. /**
  1263. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1264. * Returns the current Vector3.
  1265. */
  1266. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1267. result.x = this.x - x;
  1268. result.y = this.y - y;
  1269. result.z = this.z - z;
  1270. return this;
  1271. };
  1272. /**
  1273. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1274. */
  1275. Vector3.prototype.negate = function () {
  1276. return new Vector3(-this.x, -this.y, -this.z);
  1277. };
  1278. /**
  1279. * Multiplies the Vector3 coordinates by the float "scale".
  1280. * Returns the updated Vector3.
  1281. */
  1282. Vector3.prototype.scaleInPlace = function (scale) {
  1283. this.x *= scale;
  1284. this.y *= scale;
  1285. this.z *= scale;
  1286. return this;
  1287. };
  1288. /**
  1289. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1290. */
  1291. Vector3.prototype.scale = function (scale) {
  1292. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1293. };
  1294. /**
  1295. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1296. * Returns the current Vector3.
  1297. */
  1298. Vector3.prototype.scaleToRef = function (scale, result) {
  1299. result.x = this.x * scale;
  1300. result.y = this.y * scale;
  1301. result.z = this.z * scale;
  1302. return this;
  1303. };
  1304. /**
  1305. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1306. */
  1307. Vector3.prototype.equals = function (otherVector) {
  1308. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1309. };
  1310. /**
  1311. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1312. */
  1313. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1314. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1315. 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);
  1316. };
  1317. /**
  1318. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1319. */
  1320. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1321. return this.x === x && this.y === y && this.z === z;
  1322. };
  1323. /**
  1324. * Muliplies the current Vector3 coordinates by the passed ones.
  1325. * Returns the updated Vector3.
  1326. */
  1327. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1328. this.x *= otherVector.x;
  1329. this.y *= otherVector.y;
  1330. this.z *= otherVector.z;
  1331. return this;
  1332. };
  1333. /**
  1334. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1335. */
  1336. Vector3.prototype.multiply = function (otherVector) {
  1337. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1338. };
  1339. /**
  1340. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1341. * Returns the current Vector3.
  1342. */
  1343. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1344. result.x = this.x * otherVector.x;
  1345. result.y = this.y * otherVector.y;
  1346. result.z = this.z * otherVector.z;
  1347. return this;
  1348. };
  1349. /**
  1350. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1351. */
  1352. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1353. return new Vector3(this.x * x, this.y * y, this.z * z);
  1354. };
  1355. /**
  1356. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1357. */
  1358. Vector3.prototype.divide = function (otherVector) {
  1359. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1360. };
  1361. /**
  1362. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1363. * Returns the current Vector3.
  1364. */
  1365. Vector3.prototype.divideToRef = function (otherVector, result) {
  1366. result.x = this.x / otherVector.x;
  1367. result.y = this.y / otherVector.y;
  1368. result.z = this.z / otherVector.z;
  1369. return this;
  1370. };
  1371. /**
  1372. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1373. * Returns the updated Vector3.
  1374. */
  1375. Vector3.prototype.MinimizeInPlace = function (other) {
  1376. if (other.x < this.x)
  1377. this.x = other.x;
  1378. if (other.y < this.y)
  1379. this.y = other.y;
  1380. if (other.z < this.z)
  1381. this.z = other.z;
  1382. return this;
  1383. };
  1384. /**
  1385. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1386. * Returns the updated Vector3.
  1387. */
  1388. Vector3.prototype.MaximizeInPlace = function (other) {
  1389. if (other.x > this.x)
  1390. this.x = other.x;
  1391. if (other.y > this.y)
  1392. this.y = other.y;
  1393. if (other.z > this.z)
  1394. this.z = other.z;
  1395. return this;
  1396. };
  1397. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  1398. /**
  1399. * Return true is the vector is non uniform meaning x, y or z are not all the same.
  1400. */
  1401. get: function () {
  1402. var absX = Math.abs(this.x);
  1403. var absY = Math.abs(this.y);
  1404. if (absX !== absY) {
  1405. return true;
  1406. }
  1407. var absZ = Math.abs(this.z);
  1408. if (absX !== absZ) {
  1409. return true;
  1410. }
  1411. if (absY !== absZ) {
  1412. return true;
  1413. }
  1414. return false;
  1415. },
  1416. enumerable: true,
  1417. configurable: true
  1418. });
  1419. // Properties
  1420. /**
  1421. * Returns the length of the Vector3 (float).
  1422. */
  1423. Vector3.prototype.length = function () {
  1424. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1425. };
  1426. /**
  1427. * Returns the squared length of the Vector3 (float).
  1428. */
  1429. Vector3.prototype.lengthSquared = function () {
  1430. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1431. };
  1432. /**
  1433. * Normalize the current Vector3.
  1434. * Returns the updated Vector3.
  1435. * /!\ In place operation.
  1436. */
  1437. Vector3.prototype.normalize = function () {
  1438. var len = this.length();
  1439. if (len === 0 || len === 1.0)
  1440. return this;
  1441. var num = 1.0 / len;
  1442. this.x *= num;
  1443. this.y *= num;
  1444. this.z *= num;
  1445. return this;
  1446. };
  1447. /**
  1448. * Normalize the current Vector3 to a new vector.
  1449. * @returns the new Vector3.
  1450. */
  1451. Vector3.prototype.normalizeToNew = function () {
  1452. var normalized = new Vector3(0, 0, 0);
  1453. this.normalizeToRef(normalized);
  1454. return normalized;
  1455. };
  1456. /**
  1457. * Normalize the current Vector3 to the reference.
  1458. * @param the reference to update.
  1459. * @returns the updated Vector3.
  1460. */
  1461. Vector3.prototype.normalizeToRef = function (reference) {
  1462. var len = this.length();
  1463. if (len === 0 || len === 1.0) {
  1464. reference.set(this.x, this.y, this.z);
  1465. return reference;
  1466. }
  1467. var scale = 1.0 / len;
  1468. this.scaleToRef(scale, reference);
  1469. return reference;
  1470. };
  1471. /**
  1472. * Returns a new Vector3 copied from the current Vector3.
  1473. */
  1474. Vector3.prototype.clone = function () {
  1475. return new Vector3(this.x, this.y, this.z);
  1476. };
  1477. /**
  1478. * Copies the passed vector coordinates to the current Vector3 ones.
  1479. * Returns the updated Vector3.
  1480. */
  1481. Vector3.prototype.copyFrom = function (source) {
  1482. this.x = source.x;
  1483. this.y = source.y;
  1484. this.z = source.z;
  1485. return this;
  1486. };
  1487. /**
  1488. * Copies the passed floats to the current Vector3 coordinates.
  1489. * Returns the updated Vector3.
  1490. */
  1491. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1492. this.x = x;
  1493. this.y = y;
  1494. this.z = z;
  1495. return this;
  1496. };
  1497. /**
  1498. * Copies the passed floats to the current Vector3 coordinates.
  1499. * Returns the updated Vector3.
  1500. */
  1501. Vector3.prototype.set = function (x, y, z) {
  1502. return this.copyFromFloats(x, y, z);
  1503. };
  1504. // Statics
  1505. /**
  1506. *
  1507. */
  1508. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1509. var d0 = Vector3.Dot(vector0, axis) - size;
  1510. var d1 = Vector3.Dot(vector1, axis) - size;
  1511. var s = d0 / (d0 - d1);
  1512. return s;
  1513. };
  1514. /**
  1515. * Returns a new Vector3 set from the index "offset" of the passed array.
  1516. */
  1517. Vector3.FromArray = function (array, offset) {
  1518. if (!offset) {
  1519. offset = 0;
  1520. }
  1521. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1522. };
  1523. /**
  1524. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1525. * This function is deprecated. Use FromArray instead.
  1526. */
  1527. Vector3.FromFloatArray = function (array, offset) {
  1528. return Vector3.FromArray(array, offset);
  1529. };
  1530. /**
  1531. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  1532. */
  1533. Vector3.FromArrayToRef = function (array, offset, result) {
  1534. result.x = array[offset];
  1535. result.y = array[offset + 1];
  1536. result.z = array[offset + 2];
  1537. };
  1538. /**
  1539. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1540. * This function is deprecated. Use FromArrayToRef instead.
  1541. */
  1542. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1543. return Vector3.FromArrayToRef(array, offset, result);
  1544. };
  1545. /**
  1546. * Sets the passed vector "result" with the passed floats.
  1547. */
  1548. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1549. result.x = x;
  1550. result.y = y;
  1551. result.z = z;
  1552. };
  1553. /**
  1554. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1555. */
  1556. Vector3.Zero = function () {
  1557. return new Vector3(0.0, 0.0, 0.0);
  1558. };
  1559. /**
  1560. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  1561. */
  1562. Vector3.One = function () {
  1563. return new Vector3(1.0, 1.0, 1.0);
  1564. };
  1565. /**
  1566. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1567. */
  1568. Vector3.Up = function () {
  1569. return new Vector3(0.0, 1.0, 0.0);
  1570. };
  1571. /**
  1572. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1573. */
  1574. Vector3.Forward = function () {
  1575. return new Vector3(0.0, 0.0, 1.0);
  1576. };
  1577. /**
  1578. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1579. */
  1580. Vector3.Right = function () {
  1581. return new Vector3(1.0, 0.0, 0.0);
  1582. };
  1583. /**
  1584. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1585. */
  1586. Vector3.Left = function () {
  1587. return new Vector3(-1.0, 0.0, 0.0);
  1588. };
  1589. /**
  1590. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1591. * This method computes tranformed coordinates only, not transformed direction vectors.
  1592. */
  1593. Vector3.TransformCoordinates = function (vector, transformation) {
  1594. var result = Vector3.Zero();
  1595. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1596. return result;
  1597. };
  1598. /**
  1599. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1600. * This method computes tranformed coordinates only, not transformed direction vectors.
  1601. */
  1602. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1603. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1604. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1605. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1606. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1607. result.x = x / w;
  1608. result.y = y / w;
  1609. result.z = z / w;
  1610. };
  1611. /**
  1612. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1613. * This method computes tranformed coordinates only, not transformed direction vectors.
  1614. */
  1615. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1616. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1617. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1618. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1619. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1620. result.x = rx / rw;
  1621. result.y = ry / rw;
  1622. result.z = rz / rw;
  1623. };
  1624. /**
  1625. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1626. * This methods computes transformed normalized direction vectors only.
  1627. */
  1628. Vector3.TransformNormal = function (vector, transformation) {
  1629. var result = Vector3.Zero();
  1630. Vector3.TransformNormalToRef(vector, transformation, result);
  1631. return result;
  1632. };
  1633. /**
  1634. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1635. * This methods computes transformed normalized direction vectors only.
  1636. */
  1637. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1638. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1639. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1640. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1641. result.x = x;
  1642. result.y = y;
  1643. result.z = z;
  1644. };
  1645. /**
  1646. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1647. * This methods computes transformed normalized direction vectors only.
  1648. */
  1649. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1650. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1651. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1652. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1653. };
  1654. /**
  1655. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1656. */
  1657. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1658. var squared = amount * amount;
  1659. var cubed = amount * squared;
  1660. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1661. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1662. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1663. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1664. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1665. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1666. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1667. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1668. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1669. return new Vector3(x, y, z);
  1670. };
  1671. /**
  1672. * 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".
  1673. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1674. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1675. */
  1676. Vector3.Clamp = function (value, min, max) {
  1677. var x = value.x;
  1678. x = (x > max.x) ? max.x : x;
  1679. x = (x < min.x) ? min.x : x;
  1680. var y = value.y;
  1681. y = (y > max.y) ? max.y : y;
  1682. y = (y < min.y) ? min.y : y;
  1683. var z = value.z;
  1684. z = (z > max.z) ? max.z : z;
  1685. z = (z < min.z) ? min.z : z;
  1686. return new Vector3(x, y, z);
  1687. };
  1688. /**
  1689. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1690. */
  1691. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1692. var squared = amount * amount;
  1693. var cubed = amount * squared;
  1694. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1695. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1696. var part3 = (cubed - (2.0 * squared)) + amount;
  1697. var part4 = cubed - squared;
  1698. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1699. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1700. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1701. return new Vector3(x, y, z);
  1702. };
  1703. /**
  1704. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1705. */
  1706. Vector3.Lerp = function (start, end, amount) {
  1707. var result = new Vector3(0, 0, 0);
  1708. Vector3.LerpToRef(start, end, amount, result);
  1709. return result;
  1710. };
  1711. /**
  1712. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1713. */
  1714. Vector3.LerpToRef = function (start, end, amount, result) {
  1715. result.x = start.x + ((end.x - start.x) * amount);
  1716. result.y = start.y + ((end.y - start.y) * amount);
  1717. result.z = start.z + ((end.z - start.z) * amount);
  1718. };
  1719. /**
  1720. * Returns the dot product (float) between the vectors "left" and "right".
  1721. */
  1722. Vector3.Dot = function (left, right) {
  1723. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1724. };
  1725. /**
  1726. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1727. * The cross product is then orthogonal to both "left" and "right".
  1728. */
  1729. Vector3.Cross = function (left, right) {
  1730. var result = Vector3.Zero();
  1731. Vector3.CrossToRef(left, right, result);
  1732. return result;
  1733. };
  1734. /**
  1735. * Sets the passed vector "result" with the cross product of "left" and "right".
  1736. * The cross product is then orthogonal to both "left" and "right".
  1737. */
  1738. Vector3.CrossToRef = function (left, right, result) {
  1739. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1740. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1741. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1742. result.copyFrom(MathTmp.Vector3[0]);
  1743. };
  1744. /**
  1745. * Returns a new Vector3 as the normalization of the passed vector.
  1746. */
  1747. Vector3.Normalize = function (vector) {
  1748. var result = Vector3.Zero();
  1749. Vector3.NormalizeToRef(vector, result);
  1750. return result;
  1751. };
  1752. /**
  1753. * Sets the passed vector "result" with the normalization of the passed first vector.
  1754. */
  1755. Vector3.NormalizeToRef = function (vector, result) {
  1756. result.copyFrom(vector);
  1757. result.normalize();
  1758. };
  1759. Vector3.Project = function (vector, world, transform, viewport) {
  1760. var cw = viewport.width;
  1761. var ch = viewport.height;
  1762. var cx = viewport.x;
  1763. var cy = viewport.y;
  1764. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1765. 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);
  1766. var matrix = MathTmp.Matrix[0];
  1767. world.multiplyToRef(transform, matrix);
  1768. matrix.multiplyToRef(viewportMatrix, matrix);
  1769. return Vector3.TransformCoordinates(vector, matrix);
  1770. };
  1771. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1772. var matrix = MathTmp.Matrix[0];
  1773. world.multiplyToRef(transform, matrix);
  1774. matrix.invert();
  1775. source.x = source.x / viewportWidth * 2 - 1;
  1776. source.y = -(source.y / viewportHeight * 2 - 1);
  1777. var vector = Vector3.TransformCoordinates(source, matrix);
  1778. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1779. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1780. vector = vector.scale(1.0 / num);
  1781. }
  1782. return vector;
  1783. };
  1784. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1785. var result = Vector3.Zero();
  1786. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  1787. return result;
  1788. };
  1789. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  1790. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  1791. };
  1792. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  1793. var matrix = MathTmp.Matrix[0];
  1794. world.multiplyToRef(view, matrix);
  1795. matrix.multiplyToRef(projection, matrix);
  1796. matrix.invert();
  1797. var screenSource = MathTmp.Vector3[0];
  1798. screenSource.x = sourceX / viewportWidth * 2 - 1;
  1799. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  1800. screenSource.z = 2 * sourceZ - 1.0;
  1801. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  1802. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1803. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1804. result.scaleInPlace(1.0 / num);
  1805. }
  1806. };
  1807. Vector3.Minimize = function (left, right) {
  1808. var min = left.clone();
  1809. min.MinimizeInPlace(right);
  1810. return min;
  1811. };
  1812. Vector3.Maximize = function (left, right) {
  1813. var max = left.clone();
  1814. max.MaximizeInPlace(right);
  1815. return max;
  1816. };
  1817. /**
  1818. * Returns the distance (float) between the vectors "value1" and "value2".
  1819. */
  1820. Vector3.Distance = function (value1, value2) {
  1821. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1822. };
  1823. /**
  1824. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1825. */
  1826. Vector3.DistanceSquared = function (value1, value2) {
  1827. var x = value1.x - value2.x;
  1828. var y = value1.y - value2.y;
  1829. var z = value1.z - value2.z;
  1830. return (x * x) + (y * y) + (z * z);
  1831. };
  1832. /**
  1833. * Returns a new Vector3 located at the center between "value1" and "value2".
  1834. */
  1835. Vector3.Center = function (value1, value2) {
  1836. var center = value1.add(value2);
  1837. center.scaleInPlace(0.5);
  1838. return center;
  1839. };
  1840. /**
  1841. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1842. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1843. * to something in order to rotate it from its local system to the given target system.
  1844. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1845. * Returns a new Vector3.
  1846. */
  1847. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1848. var rotation = Vector3.Zero();
  1849. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1850. return rotation;
  1851. };
  1852. /**
  1853. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1854. */
  1855. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1856. var quat = MathTmp.Quaternion[0];
  1857. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1858. quat.toEulerAnglesToRef(ref);
  1859. };
  1860. return Vector3;
  1861. }());
  1862. BABYLON.Vector3 = Vector3;
  1863. //Vector4 class created for EulerAngle class conversion to Quaternion
  1864. var Vector4 = /** @class */ (function () {
  1865. /**
  1866. * Creates a Vector4 object from the passed floats.
  1867. */
  1868. function Vector4(x, y, z, w) {
  1869. this.x = x;
  1870. this.y = y;
  1871. this.z = z;
  1872. this.w = w;
  1873. }
  1874. /**
  1875. * Returns the string with the Vector4 coordinates.
  1876. */
  1877. Vector4.prototype.toString = function () {
  1878. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1879. };
  1880. /**
  1881. * Returns the string "Vector4".
  1882. */
  1883. Vector4.prototype.getClassName = function () {
  1884. return "Vector4";
  1885. };
  1886. /**
  1887. * Returns the Vector4 hash code.
  1888. */
  1889. Vector4.prototype.getHashCode = function () {
  1890. var hash = this.x || 0;
  1891. hash = (hash * 397) ^ (this.y || 0);
  1892. hash = (hash * 397) ^ (this.z || 0);
  1893. hash = (hash * 397) ^ (this.w || 0);
  1894. return hash;
  1895. };
  1896. // Operators
  1897. /**
  1898. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1899. */
  1900. Vector4.prototype.asArray = function () {
  1901. var result = new Array();
  1902. this.toArray(result, 0);
  1903. return result;
  1904. };
  1905. /**
  1906. * Populates the passed array from the passed index with the Vector4 coordinates.
  1907. * Returns the Vector4.
  1908. */
  1909. Vector4.prototype.toArray = function (array, index) {
  1910. if (index === undefined) {
  1911. index = 0;
  1912. }
  1913. array[index] = this.x;
  1914. array[index + 1] = this.y;
  1915. array[index + 2] = this.z;
  1916. array[index + 3] = this.w;
  1917. return this;
  1918. };
  1919. /**
  1920. * Adds the passed vector to the current Vector4.
  1921. * Returns the updated Vector4.
  1922. */
  1923. Vector4.prototype.addInPlace = function (otherVector) {
  1924. this.x += otherVector.x;
  1925. this.y += otherVector.y;
  1926. this.z += otherVector.z;
  1927. this.w += otherVector.w;
  1928. return this;
  1929. };
  1930. /**
  1931. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1932. */
  1933. Vector4.prototype.add = function (otherVector) {
  1934. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1935. };
  1936. /**
  1937. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1938. * Returns the current Vector4.
  1939. */
  1940. Vector4.prototype.addToRef = function (otherVector, result) {
  1941. result.x = this.x + otherVector.x;
  1942. result.y = this.y + otherVector.y;
  1943. result.z = this.z + otherVector.z;
  1944. result.w = this.w + otherVector.w;
  1945. return this;
  1946. };
  1947. /**
  1948. * Subtract in place the passed vector from the current Vector4.
  1949. * Returns the updated Vector4.
  1950. */
  1951. Vector4.prototype.subtractInPlace = function (otherVector) {
  1952. this.x -= otherVector.x;
  1953. this.y -= otherVector.y;
  1954. this.z -= otherVector.z;
  1955. this.w -= otherVector.w;
  1956. return this;
  1957. };
  1958. /**
  1959. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1960. */
  1961. Vector4.prototype.subtract = function (otherVector) {
  1962. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1963. };
  1964. /**
  1965. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1966. * Returns the current Vector4.
  1967. */
  1968. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1969. result.x = this.x - otherVector.x;
  1970. result.y = this.y - otherVector.y;
  1971. result.z = this.z - otherVector.z;
  1972. result.w = this.w - otherVector.w;
  1973. return this;
  1974. };
  1975. /**
  1976. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1977. */
  1978. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1979. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1980. };
  1981. /**
  1982. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1983. * Returns the current Vector4.
  1984. */
  1985. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1986. result.x = this.x - x;
  1987. result.y = this.y - y;
  1988. result.z = this.z - z;
  1989. result.w = this.w - w;
  1990. return this;
  1991. };
  1992. /**
  1993. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1994. */
  1995. Vector4.prototype.negate = function () {
  1996. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1997. };
  1998. /**
  1999. * Multiplies the current Vector4 coordinates by scale (float).
  2000. * Returns the updated Vector4.
  2001. */
  2002. Vector4.prototype.scaleInPlace = function (scale) {
  2003. this.x *= scale;
  2004. this.y *= scale;
  2005. this.z *= scale;
  2006. this.w *= scale;
  2007. return this;
  2008. };
  2009. /**
  2010. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  2011. */
  2012. Vector4.prototype.scale = function (scale) {
  2013. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  2014. };
  2015. /**
  2016. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  2017. * Returns the current Vector4.
  2018. */
  2019. Vector4.prototype.scaleToRef = function (scale, result) {
  2020. result.x = this.x * scale;
  2021. result.y = this.y * scale;
  2022. result.z = this.z * scale;
  2023. result.w = this.w * scale;
  2024. return this;
  2025. };
  2026. /**
  2027. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  2028. */
  2029. Vector4.prototype.equals = function (otherVector) {
  2030. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  2031. };
  2032. /**
  2033. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  2034. */
  2035. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2036. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2037. return otherVector
  2038. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  2039. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  2040. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  2041. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  2042. };
  2043. /**
  2044. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  2045. */
  2046. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  2047. return this.x === x && this.y === y && this.z === z && this.w === w;
  2048. };
  2049. /**
  2050. * Multiplies in place the current Vector4 by the passed one.
  2051. * Returns the updated Vector4.
  2052. */
  2053. Vector4.prototype.multiplyInPlace = function (otherVector) {
  2054. this.x *= otherVector.x;
  2055. this.y *= otherVector.y;
  2056. this.z *= otherVector.z;
  2057. this.w *= otherVector.w;
  2058. return this;
  2059. };
  2060. /**
  2061. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  2062. */
  2063. Vector4.prototype.multiply = function (otherVector) {
  2064. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  2065. };
  2066. /**
  2067. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  2068. * Returns the current Vector4.
  2069. */
  2070. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  2071. result.x = this.x * otherVector.x;
  2072. result.y = this.y * otherVector.y;
  2073. result.z = this.z * otherVector.z;
  2074. result.w = this.w * otherVector.w;
  2075. return this;
  2076. };
  2077. /**
  2078. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  2079. */
  2080. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  2081. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  2082. };
  2083. /**
  2084. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  2085. */
  2086. Vector4.prototype.divide = function (otherVector) {
  2087. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  2088. };
  2089. /**
  2090. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  2091. * Returns the current Vector4.
  2092. */
  2093. Vector4.prototype.divideToRef = function (otherVector, result) {
  2094. result.x = this.x / otherVector.x;
  2095. result.y = this.y / otherVector.y;
  2096. result.z = this.z / otherVector.z;
  2097. result.w = this.w / otherVector.w;
  2098. return this;
  2099. };
  2100. /**
  2101. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  2102. */
  2103. Vector4.prototype.MinimizeInPlace = function (other) {
  2104. if (other.x < this.x)
  2105. this.x = other.x;
  2106. if (other.y < this.y)
  2107. this.y = other.y;
  2108. if (other.z < this.z)
  2109. this.z = other.z;
  2110. if (other.w < this.w)
  2111. this.w = other.w;
  2112. return this;
  2113. };
  2114. /**
  2115. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  2116. */
  2117. Vector4.prototype.MaximizeInPlace = function (other) {
  2118. if (other.x > this.x)
  2119. this.x = other.x;
  2120. if (other.y > this.y)
  2121. this.y = other.y;
  2122. if (other.z > this.z)
  2123. this.z = other.z;
  2124. if (other.w > this.w)
  2125. this.w = other.w;
  2126. return this;
  2127. };
  2128. // Properties
  2129. /**
  2130. * Returns the Vector4 length (float).
  2131. */
  2132. Vector4.prototype.length = function () {
  2133. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2134. };
  2135. /**
  2136. * Returns the Vector4 squared length (float).
  2137. */
  2138. Vector4.prototype.lengthSquared = function () {
  2139. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2140. };
  2141. // Methods
  2142. /**
  2143. * Normalizes in place the Vector4.
  2144. * Returns the updated Vector4.
  2145. */
  2146. Vector4.prototype.normalize = function () {
  2147. var len = this.length();
  2148. if (len === 0)
  2149. return this;
  2150. var num = 1.0 / len;
  2151. this.x *= num;
  2152. this.y *= num;
  2153. this.z *= num;
  2154. this.w *= num;
  2155. return this;
  2156. };
  2157. /**
  2158. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  2159. */
  2160. Vector4.prototype.toVector3 = function () {
  2161. return new Vector3(this.x, this.y, this.z);
  2162. };
  2163. /**
  2164. * Returns a new Vector4 copied from the current one.
  2165. */
  2166. Vector4.prototype.clone = function () {
  2167. return new Vector4(this.x, this.y, this.z, this.w);
  2168. };
  2169. /**
  2170. * Updates the current Vector4 with the passed one coordinates.
  2171. * Returns the updated Vector4.
  2172. */
  2173. Vector4.prototype.copyFrom = function (source) {
  2174. this.x = source.x;
  2175. this.y = source.y;
  2176. this.z = source.z;
  2177. this.w = source.w;
  2178. return this;
  2179. };
  2180. /**
  2181. * Updates the current Vector4 coordinates with the passed floats.
  2182. * Returns the updated Vector4.
  2183. */
  2184. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  2185. this.x = x;
  2186. this.y = y;
  2187. this.z = z;
  2188. this.w = w;
  2189. return this;
  2190. };
  2191. /**
  2192. * Updates the current Vector4 coordinates with the passed floats.
  2193. * Returns the updated Vector4.
  2194. */
  2195. Vector4.prototype.set = function (x, y, z, w) {
  2196. return this.copyFromFloats(x, y, z, w);
  2197. };
  2198. // Statics
  2199. /**
  2200. * Returns a new Vector4 set from the starting index of the passed array.
  2201. */
  2202. Vector4.FromArray = function (array, offset) {
  2203. if (!offset) {
  2204. offset = 0;
  2205. }
  2206. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2207. };
  2208. /**
  2209. * Updates the passed vector "result" from the starting index of the passed array.
  2210. */
  2211. Vector4.FromArrayToRef = function (array, offset, result) {
  2212. result.x = array[offset];
  2213. result.y = array[offset + 1];
  2214. result.z = array[offset + 2];
  2215. result.w = array[offset + 3];
  2216. };
  2217. /**
  2218. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2219. */
  2220. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2221. Vector4.FromArrayToRef(array, offset, result);
  2222. };
  2223. /**
  2224. * Updates the passed vector "result" coordinates from the passed floats.
  2225. */
  2226. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2227. result.x = x;
  2228. result.y = y;
  2229. result.z = z;
  2230. result.w = w;
  2231. };
  2232. /**
  2233. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2234. */
  2235. Vector4.Zero = function () {
  2236. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2237. };
  2238. /**
  2239. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  2240. */
  2241. Vector4.One = function () {
  2242. return new Vector4(1.0, 1.0, 1.0, 1.0);
  2243. };
  2244. /**
  2245. * Returns a new normalized Vector4 from the passed one.
  2246. */
  2247. Vector4.Normalize = function (vector) {
  2248. var result = Vector4.Zero();
  2249. Vector4.NormalizeToRef(vector, result);
  2250. return result;
  2251. };
  2252. /**
  2253. * Updates the passed vector "result" from the normalization of the passed one.
  2254. */
  2255. Vector4.NormalizeToRef = function (vector, result) {
  2256. result.copyFrom(vector);
  2257. result.normalize();
  2258. };
  2259. Vector4.Minimize = function (left, right) {
  2260. var min = left.clone();
  2261. min.MinimizeInPlace(right);
  2262. return min;
  2263. };
  2264. Vector4.Maximize = function (left, right) {
  2265. var max = left.clone();
  2266. max.MaximizeInPlace(right);
  2267. return max;
  2268. };
  2269. /**
  2270. * Returns the distance (float) between the vectors "value1" and "value2".
  2271. */
  2272. Vector4.Distance = function (value1, value2) {
  2273. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2274. };
  2275. /**
  2276. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2277. */
  2278. Vector4.DistanceSquared = function (value1, value2) {
  2279. var x = value1.x - value2.x;
  2280. var y = value1.y - value2.y;
  2281. var z = value1.z - value2.z;
  2282. var w = value1.w - value2.w;
  2283. return (x * x) + (y * y) + (z * z) + (w * w);
  2284. };
  2285. /**
  2286. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2287. */
  2288. Vector4.Center = function (value1, value2) {
  2289. var center = value1.add(value2);
  2290. center.scaleInPlace(0.5);
  2291. return center;
  2292. };
  2293. /**
  2294. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2295. * This methods computes transformed normalized direction vectors only.
  2296. */
  2297. Vector4.TransformNormal = function (vector, transformation) {
  2298. var result = Vector4.Zero();
  2299. Vector4.TransformNormalToRef(vector, transformation, result);
  2300. return result;
  2301. };
  2302. /**
  2303. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2304. * This methods computes transformed normalized direction vectors only.
  2305. */
  2306. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2307. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2308. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2309. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2310. result.x = x;
  2311. result.y = y;
  2312. result.z = z;
  2313. result.w = vector.w;
  2314. };
  2315. /**
  2316. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2317. * This methods computes transformed normalized direction vectors only.
  2318. */
  2319. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2320. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2321. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2322. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2323. result.w = w;
  2324. };
  2325. return Vector4;
  2326. }());
  2327. BABYLON.Vector4 = Vector4;
  2328. var Size = /** @class */ (function () {
  2329. /**
  2330. * Creates a Size object from the passed width and height (floats).
  2331. */
  2332. function Size(width, height) {
  2333. this.width = width;
  2334. this.height = height;
  2335. }
  2336. // Returns a string with the Size width and height.
  2337. Size.prototype.toString = function () {
  2338. return "{W: " + this.width + ", H: " + this.height + "}";
  2339. };
  2340. /**
  2341. * Returns the string "Size"
  2342. */
  2343. Size.prototype.getClassName = function () {
  2344. return "Size";
  2345. };
  2346. /**
  2347. * Returns the Size hash code.
  2348. */
  2349. Size.prototype.getHashCode = function () {
  2350. var hash = this.width || 0;
  2351. hash = (hash * 397) ^ (this.height || 0);
  2352. return hash;
  2353. };
  2354. /**
  2355. * Updates the current size from the passed one.
  2356. * Returns the updated Size.
  2357. */
  2358. Size.prototype.copyFrom = function (src) {
  2359. this.width = src.width;
  2360. this.height = src.height;
  2361. };
  2362. /**
  2363. * Updates in place the current Size from the passed floats.
  2364. * Returns the updated Size.
  2365. */
  2366. Size.prototype.copyFromFloats = function (width, height) {
  2367. this.width = width;
  2368. this.height = height;
  2369. return this;
  2370. };
  2371. /**
  2372. * Updates in place the current Size from the passed floats.
  2373. * Returns the updated Size.
  2374. */
  2375. Size.prototype.set = function (width, height) {
  2376. return this.copyFromFloats(width, height);
  2377. };
  2378. /**
  2379. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2380. */
  2381. Size.prototype.multiplyByFloats = function (w, h) {
  2382. return new Size(this.width * w, this.height * h);
  2383. };
  2384. /**
  2385. * Returns a new Size copied from the passed one.
  2386. */
  2387. Size.prototype.clone = function () {
  2388. return new Size(this.width, this.height);
  2389. };
  2390. /**
  2391. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2392. */
  2393. Size.prototype.equals = function (other) {
  2394. if (!other) {
  2395. return false;
  2396. }
  2397. return (this.width === other.width) && (this.height === other.height);
  2398. };
  2399. Object.defineProperty(Size.prototype, "surface", {
  2400. /**
  2401. * Returns the surface of the Size : width * height (float).
  2402. */
  2403. get: function () {
  2404. return this.width * this.height;
  2405. },
  2406. enumerable: true,
  2407. configurable: true
  2408. });
  2409. /**
  2410. * Returns a new Size set to (0.0, 0.0)
  2411. */
  2412. Size.Zero = function () {
  2413. return new Size(0.0, 0.0);
  2414. };
  2415. /**
  2416. * Returns a new Size set as the addition result of the current Size and the passed one.
  2417. */
  2418. Size.prototype.add = function (otherSize) {
  2419. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2420. return r;
  2421. };
  2422. /**
  2423. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2424. */
  2425. Size.prototype.subtract = function (otherSize) {
  2426. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2427. return r;
  2428. };
  2429. /**
  2430. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2431. */
  2432. Size.Lerp = function (start, end, amount) {
  2433. var w = start.width + ((end.width - start.width) * amount);
  2434. var h = start.height + ((end.height - start.height) * amount);
  2435. return new Size(w, h);
  2436. };
  2437. return Size;
  2438. }());
  2439. BABYLON.Size = Size;
  2440. var Quaternion = /** @class */ (function () {
  2441. /**
  2442. * Creates a new Quaternion from the passed floats.
  2443. */
  2444. function Quaternion(x, y, z, w) {
  2445. if (x === void 0) { x = 0.0; }
  2446. if (y === void 0) { y = 0.0; }
  2447. if (z === void 0) { z = 0.0; }
  2448. if (w === void 0) { w = 1.0; }
  2449. this.x = x;
  2450. this.y = y;
  2451. this.z = z;
  2452. this.w = w;
  2453. }
  2454. /**
  2455. * Returns a string with the Quaternion coordinates.
  2456. */
  2457. Quaternion.prototype.toString = function () {
  2458. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2459. };
  2460. /**
  2461. * Returns the string "Quaternion".
  2462. */
  2463. Quaternion.prototype.getClassName = function () {
  2464. return "Quaternion";
  2465. };
  2466. /**
  2467. * Returns the Quaternion hash code.
  2468. */
  2469. Quaternion.prototype.getHashCode = function () {
  2470. var hash = this.x || 0;
  2471. hash = (hash * 397) ^ (this.y || 0);
  2472. hash = (hash * 397) ^ (this.z || 0);
  2473. hash = (hash * 397) ^ (this.w || 0);
  2474. return hash;
  2475. };
  2476. /**
  2477. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2478. */
  2479. Quaternion.prototype.asArray = function () {
  2480. return [this.x, this.y, this.z, this.w];
  2481. };
  2482. /**
  2483. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2484. */
  2485. Quaternion.prototype.equals = function (otherQuaternion) {
  2486. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2487. };
  2488. /**
  2489. * Returns a new Quaternion copied from the current one.
  2490. */
  2491. Quaternion.prototype.clone = function () {
  2492. return new Quaternion(this.x, this.y, this.z, this.w);
  2493. };
  2494. /**
  2495. * Updates the current Quaternion from the passed one coordinates.
  2496. * Returns the updated Quaterion.
  2497. */
  2498. Quaternion.prototype.copyFrom = function (other) {
  2499. this.x = other.x;
  2500. this.y = other.y;
  2501. this.z = other.z;
  2502. this.w = other.w;
  2503. return this;
  2504. };
  2505. /**
  2506. * Updates the current Quaternion from the passed float coordinates.
  2507. * Returns the updated Quaterion.
  2508. */
  2509. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2510. this.x = x;
  2511. this.y = y;
  2512. this.z = z;
  2513. this.w = w;
  2514. return this;
  2515. };
  2516. /**
  2517. * Updates the current Quaternion from the passed float coordinates.
  2518. * Returns the updated Quaterion.
  2519. */
  2520. Quaternion.prototype.set = function (x, y, z, w) {
  2521. return this.copyFromFloats(x, y, z, w);
  2522. };
  2523. /**
  2524. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2525. */
  2526. Quaternion.prototype.add = function (other) {
  2527. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2528. };
  2529. /**
  2530. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2531. */
  2532. Quaternion.prototype.subtract = function (other) {
  2533. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2534. };
  2535. /**
  2536. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2537. */
  2538. Quaternion.prototype.scale = function (value) {
  2539. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2540. };
  2541. /**
  2542. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2543. */
  2544. Quaternion.prototype.multiply = function (q1) {
  2545. var result = new Quaternion(0, 0, 0, 1.0);
  2546. this.multiplyToRef(q1, result);
  2547. return result;
  2548. };
  2549. /**
  2550. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2551. * Returns the current Quaternion.
  2552. */
  2553. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2554. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2555. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2556. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2557. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2558. result.copyFromFloats(x, y, z, w);
  2559. return this;
  2560. };
  2561. /**
  2562. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2563. * Returns the updated Quaternion.
  2564. */
  2565. Quaternion.prototype.multiplyInPlace = function (q1) {
  2566. this.multiplyToRef(q1, this);
  2567. return this;
  2568. };
  2569. /**
  2570. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2571. * Returns the current Quaternion.
  2572. */
  2573. Quaternion.prototype.conjugateToRef = function (ref) {
  2574. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2575. return this;
  2576. };
  2577. /**
  2578. * Conjugates in place the current Quaternion.
  2579. * Returns the updated Quaternion.
  2580. */
  2581. Quaternion.prototype.conjugateInPlace = function () {
  2582. this.x *= -1;
  2583. this.y *= -1;
  2584. this.z *= -1;
  2585. return this;
  2586. };
  2587. /**
  2588. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2589. */
  2590. Quaternion.prototype.conjugate = function () {
  2591. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2592. return result;
  2593. };
  2594. /**
  2595. * Returns the Quaternion length (float).
  2596. */
  2597. Quaternion.prototype.length = function () {
  2598. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2599. };
  2600. /**
  2601. * Normalize in place the current Quaternion.
  2602. * Returns the updated Quaternion.
  2603. */
  2604. Quaternion.prototype.normalize = function () {
  2605. var length = 1.0 / this.length();
  2606. this.x *= length;
  2607. this.y *= length;
  2608. this.z *= length;
  2609. this.w *= length;
  2610. return this;
  2611. };
  2612. /**
  2613. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2614. */
  2615. Quaternion.prototype.toEulerAngles = function (order) {
  2616. if (order === void 0) { order = "YZX"; }
  2617. var result = Vector3.Zero();
  2618. this.toEulerAnglesToRef(result, order);
  2619. return result;
  2620. };
  2621. /**
  2622. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2623. * Returns the current Quaternion.
  2624. */
  2625. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2626. if (order === void 0) { order = "YZX"; }
  2627. var qz = this.z;
  2628. var qx = this.x;
  2629. var qy = this.y;
  2630. var qw = this.w;
  2631. var sqw = qw * qw;
  2632. var sqz = qz * qz;
  2633. var sqx = qx * qx;
  2634. var sqy = qy * qy;
  2635. var zAxisY = qy * qz - qx * qw;
  2636. var limit = .4999999;
  2637. if (zAxisY < -limit) {
  2638. result.y = 2 * Math.atan2(qy, qw);
  2639. result.x = Math.PI / 2;
  2640. result.z = 0;
  2641. }
  2642. else if (zAxisY > limit) {
  2643. result.y = 2 * Math.atan2(qy, qw);
  2644. result.x = -Math.PI / 2;
  2645. result.z = 0;
  2646. }
  2647. else {
  2648. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2649. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2650. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2651. }
  2652. return this;
  2653. };
  2654. /**
  2655. * Updates the passed rotation matrix with the current Quaternion values.
  2656. * Returns the current Quaternion.
  2657. */
  2658. Quaternion.prototype.toRotationMatrix = function (result) {
  2659. var xx = this.x * this.x;
  2660. var yy = this.y * this.y;
  2661. var zz = this.z * this.z;
  2662. var xy = this.x * this.y;
  2663. var zw = this.z * this.w;
  2664. var zx = this.z * this.x;
  2665. var yw = this.y * this.w;
  2666. var yz = this.y * this.z;
  2667. var xw = this.x * this.w;
  2668. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2669. result.m[1] = 2.0 * (xy + zw);
  2670. result.m[2] = 2.0 * (zx - yw);
  2671. result.m[3] = 0;
  2672. result.m[4] = 2.0 * (xy - zw);
  2673. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2674. result.m[6] = 2.0 * (yz + xw);
  2675. result.m[7] = 0;
  2676. result.m[8] = 2.0 * (zx + yw);
  2677. result.m[9] = 2.0 * (yz - xw);
  2678. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2679. result.m[11] = 0;
  2680. result.m[12] = 0;
  2681. result.m[13] = 0;
  2682. result.m[14] = 0;
  2683. result.m[15] = 1.0;
  2684. result._markAsUpdated();
  2685. return this;
  2686. };
  2687. /**
  2688. * Updates the current Quaternion from the passed rotation matrix values.
  2689. * Returns the updated Quaternion.
  2690. */
  2691. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2692. Quaternion.FromRotationMatrixToRef(matrix, this);
  2693. return this;
  2694. };
  2695. // Statics
  2696. /**
  2697. * Returns a new Quaternion set from the passed rotation matrix values.
  2698. */
  2699. Quaternion.FromRotationMatrix = function (matrix) {
  2700. var result = new Quaternion();
  2701. Quaternion.FromRotationMatrixToRef(matrix, result);
  2702. return result;
  2703. };
  2704. /**
  2705. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2706. */
  2707. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2708. var data = matrix.m;
  2709. var m11 = data[0], m12 = data[4], m13 = data[8];
  2710. var m21 = data[1], m22 = data[5], m23 = data[9];
  2711. var m31 = data[2], m32 = data[6], m33 = data[10];
  2712. var trace = m11 + m22 + m33;
  2713. var s;
  2714. if (trace > 0) {
  2715. s = 0.5 / Math.sqrt(trace + 1.0);
  2716. result.w = 0.25 / s;
  2717. result.x = (m32 - m23) * s;
  2718. result.y = (m13 - m31) * s;
  2719. result.z = (m21 - m12) * s;
  2720. }
  2721. else if (m11 > m22 && m11 > m33) {
  2722. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2723. result.w = (m32 - m23) / s;
  2724. result.x = 0.25 * s;
  2725. result.y = (m12 + m21) / s;
  2726. result.z = (m13 + m31) / s;
  2727. }
  2728. else if (m22 > m33) {
  2729. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2730. result.w = (m13 - m31) / s;
  2731. result.x = (m12 + m21) / s;
  2732. result.y = 0.25 * s;
  2733. result.z = (m23 + m32) / s;
  2734. }
  2735. else {
  2736. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2737. result.w = (m21 - m12) / s;
  2738. result.x = (m13 + m31) / s;
  2739. result.y = (m23 + m32) / s;
  2740. result.z = 0.25 * s;
  2741. }
  2742. };
  2743. /**
  2744. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2745. */
  2746. Quaternion.Zero = function () {
  2747. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2748. };
  2749. /**
  2750. * Returns a new Quaternion as the inverted current Quaternion.
  2751. */
  2752. Quaternion.Inverse = function (q) {
  2753. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2754. };
  2755. /**
  2756. * Returns the identity Quaternion.
  2757. */
  2758. Quaternion.Identity = function () {
  2759. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2760. };
  2761. Quaternion.IsIdentity = function (quaternion) {
  2762. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2763. };
  2764. /**
  2765. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2766. */
  2767. Quaternion.RotationAxis = function (axis, angle) {
  2768. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2769. };
  2770. /**
  2771. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2772. */
  2773. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2774. var sin = Math.sin(angle / 2);
  2775. axis.normalize();
  2776. result.w = Math.cos(angle / 2);
  2777. result.x = axis.x * sin;
  2778. result.y = axis.y * sin;
  2779. result.z = axis.z * sin;
  2780. return result;
  2781. };
  2782. /**
  2783. * Retuns a new Quaternion set from the starting index of the passed array.
  2784. */
  2785. Quaternion.FromArray = function (array, offset) {
  2786. if (!offset) {
  2787. offset = 0;
  2788. }
  2789. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2790. };
  2791. /**
  2792. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2793. */
  2794. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2795. var q = new Quaternion();
  2796. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2797. return q;
  2798. };
  2799. /**
  2800. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2801. */
  2802. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2803. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2804. var halfRoll = roll * 0.5;
  2805. var halfPitch = pitch * 0.5;
  2806. var halfYaw = yaw * 0.5;
  2807. var sinRoll = Math.sin(halfRoll);
  2808. var cosRoll = Math.cos(halfRoll);
  2809. var sinPitch = Math.sin(halfPitch);
  2810. var cosPitch = Math.cos(halfPitch);
  2811. var sinYaw = Math.sin(halfYaw);
  2812. var cosYaw = Math.cos(halfYaw);
  2813. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2814. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2815. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2816. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2817. };
  2818. /**
  2819. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2820. */
  2821. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2822. var result = new Quaternion();
  2823. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2824. return result;
  2825. };
  2826. /**
  2827. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2828. */
  2829. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2830. // Produces a quaternion from Euler angles in the z-x-z orientation
  2831. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2832. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2833. var halfBeta = beta * 0.5;
  2834. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2835. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2836. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2837. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2838. };
  2839. /**
  2840. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2841. * cf to Vector3.RotationFromAxis() documentation.
  2842. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2843. */
  2844. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2845. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2846. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2847. return quat;
  2848. };
  2849. /**
  2850. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2851. * cf to Vector3.RotationFromAxis() documentation.
  2852. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2853. */
  2854. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2855. var rotMat = MathTmp.Matrix[0];
  2856. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2857. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2858. };
  2859. Quaternion.Slerp = function (left, right, amount) {
  2860. var result = Quaternion.Identity();
  2861. Quaternion.SlerpToRef(left, right, amount, result);
  2862. return result;
  2863. };
  2864. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2865. var num2;
  2866. var num3;
  2867. var num = amount;
  2868. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2869. var flag = false;
  2870. if (num4 < 0) {
  2871. flag = true;
  2872. num4 = -num4;
  2873. }
  2874. if (num4 > 0.999999) {
  2875. num3 = 1 - num;
  2876. num2 = flag ? -num : num;
  2877. }
  2878. else {
  2879. var num5 = Math.acos(num4);
  2880. var num6 = (1.0 / Math.sin(num5));
  2881. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2882. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2883. }
  2884. result.x = (num3 * left.x) + (num2 * right.x);
  2885. result.y = (num3 * left.y) + (num2 * right.y);
  2886. result.z = (num3 * left.z) + (num2 * right.z);
  2887. result.w = (num3 * left.w) + (num2 * right.w);
  2888. };
  2889. /**
  2890. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2891. */
  2892. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2893. var squared = amount * amount;
  2894. var cubed = amount * squared;
  2895. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2896. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2897. var part3 = (cubed - (2.0 * squared)) + amount;
  2898. var part4 = cubed - squared;
  2899. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2900. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2901. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2902. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2903. return new Quaternion(x, y, z, w);
  2904. };
  2905. return Quaternion;
  2906. }());
  2907. BABYLON.Quaternion = Quaternion;
  2908. var Matrix = /** @class */ (function () {
  2909. function Matrix() {
  2910. this._isIdentity = false;
  2911. this._isIdentityDirty = true;
  2912. this.m = new Float32Array(16);
  2913. this._markAsUpdated();
  2914. }
  2915. Matrix.prototype._markAsUpdated = function () {
  2916. this.updateFlag = Matrix._updateFlagSeed++;
  2917. this._isIdentityDirty = true;
  2918. };
  2919. // Properties
  2920. /**
  2921. * Boolean : True is the matrix is the identity matrix
  2922. */
  2923. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  2924. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  2925. if (this._isIdentityDirty) {
  2926. this._isIdentityDirty = false;
  2927. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  2928. this._isIdentity = false;
  2929. }
  2930. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2931. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2932. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2933. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  2934. this._isIdentity = false;
  2935. }
  2936. else {
  2937. this._isIdentity = true;
  2938. }
  2939. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  2940. this._isIdentity = false;
  2941. }
  2942. }
  2943. return this._isIdentity;
  2944. };
  2945. /**
  2946. * Returns the matrix determinant (float).
  2947. */
  2948. Matrix.prototype.determinant = function () {
  2949. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2950. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2951. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2952. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2953. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2954. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2955. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2956. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2957. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2958. };
  2959. // Methods
  2960. /**
  2961. * Returns the matrix underlying array.
  2962. */
  2963. Matrix.prototype.toArray = function () {
  2964. return this.m;
  2965. };
  2966. /**
  2967. * Returns the matrix underlying array.
  2968. */
  2969. Matrix.prototype.asArray = function () {
  2970. return this.toArray();
  2971. };
  2972. /**
  2973. * Inverts in place the Matrix.
  2974. * Returns the Matrix inverted.
  2975. */
  2976. Matrix.prototype.invert = function () {
  2977. this.invertToRef(this);
  2978. return this;
  2979. };
  2980. /**
  2981. * Sets all the matrix elements to zero.
  2982. * Returns the Matrix.
  2983. */
  2984. Matrix.prototype.reset = function () {
  2985. for (var index = 0; index < 16; index++) {
  2986. this.m[index] = 0.0;
  2987. }
  2988. this._markAsUpdated();
  2989. return this;
  2990. };
  2991. /**
  2992. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2993. */
  2994. Matrix.prototype.add = function (other) {
  2995. var result = new Matrix();
  2996. this.addToRef(other, result);
  2997. return result;
  2998. };
  2999. /**
  3000. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  3001. * Returns the Matrix.
  3002. */
  3003. Matrix.prototype.addToRef = function (other, result) {
  3004. for (var index = 0; index < 16; index++) {
  3005. result.m[index] = this.m[index] + other.m[index];
  3006. }
  3007. result._markAsUpdated();
  3008. return this;
  3009. };
  3010. /**
  3011. * Adds in place the passed matrix to the current Matrix.
  3012. * Returns the updated Matrix.
  3013. */
  3014. Matrix.prototype.addToSelf = function (other) {
  3015. for (var index = 0; index < 16; index++) {
  3016. this.m[index] += other.m[index];
  3017. }
  3018. this._markAsUpdated();
  3019. return this;
  3020. };
  3021. /**
  3022. * Sets the passed matrix with the current inverted Matrix.
  3023. * Returns the unmodified current Matrix.
  3024. */
  3025. Matrix.prototype.invertToRef = function (other) {
  3026. var l1 = this.m[0];
  3027. var l2 = this.m[1];
  3028. var l3 = this.m[2];
  3029. var l4 = this.m[3];
  3030. var l5 = this.m[4];
  3031. var l6 = this.m[5];
  3032. var l7 = this.m[6];
  3033. var l8 = this.m[7];
  3034. var l9 = this.m[8];
  3035. var l10 = this.m[9];
  3036. var l11 = this.m[10];
  3037. var l12 = this.m[11];
  3038. var l13 = this.m[12];
  3039. var l14 = this.m[13];
  3040. var l15 = this.m[14];
  3041. var l16 = this.m[15];
  3042. var l17 = (l11 * l16) - (l12 * l15);
  3043. var l18 = (l10 * l16) - (l12 * l14);
  3044. var l19 = (l10 * l15) - (l11 * l14);
  3045. var l20 = (l9 * l16) - (l12 * l13);
  3046. var l21 = (l9 * l15) - (l11 * l13);
  3047. var l22 = (l9 * l14) - (l10 * l13);
  3048. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  3049. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  3050. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  3051. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  3052. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  3053. var l28 = (l7 * l16) - (l8 * l15);
  3054. var l29 = (l6 * l16) - (l8 * l14);
  3055. var l30 = (l6 * l15) - (l7 * l14);
  3056. var l31 = (l5 * l16) - (l8 * l13);
  3057. var l32 = (l5 * l15) - (l7 * l13);
  3058. var l33 = (l5 * l14) - (l6 * l13);
  3059. var l34 = (l7 * l12) - (l8 * l11);
  3060. var l35 = (l6 * l12) - (l8 * l10);
  3061. var l36 = (l6 * l11) - (l7 * l10);
  3062. var l37 = (l5 * l12) - (l8 * l9);
  3063. var l38 = (l5 * l11) - (l7 * l9);
  3064. var l39 = (l5 * l10) - (l6 * l9);
  3065. other.m[0] = l23 * l27;
  3066. other.m[4] = l24 * l27;
  3067. other.m[8] = l25 * l27;
  3068. other.m[12] = l26 * l27;
  3069. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  3070. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  3071. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  3072. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  3073. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  3074. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  3075. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  3076. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  3077. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  3078. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  3079. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  3080. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  3081. other._markAsUpdated();
  3082. return this;
  3083. };
  3084. /**
  3085. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  3086. * Returns the updated Matrix.
  3087. */
  3088. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  3089. this.m[12] = x;
  3090. this.m[13] = y;
  3091. this.m[14] = z;
  3092. this._markAsUpdated();
  3093. return this;
  3094. };
  3095. /**
  3096. * Inserts the translation vector in the current Matrix.
  3097. * Returns the updated Matrix.
  3098. */
  3099. Matrix.prototype.setTranslation = function (vector3) {
  3100. this.m[12] = vector3.x;
  3101. this.m[13] = vector3.y;
  3102. this.m[14] = vector3.z;
  3103. this._markAsUpdated();
  3104. return this;
  3105. };
  3106. /**
  3107. * Returns a new Vector3 as the extracted translation from the Matrix.
  3108. */
  3109. Matrix.prototype.getTranslation = function () {
  3110. return new Vector3(this.m[12], this.m[13], this.m[14]);
  3111. };
  3112. /**
  3113. * Fill a Vector3 with the extracted translation from the Matrix.
  3114. */
  3115. Matrix.prototype.getTranslationToRef = function (result) {
  3116. result.x = this.m[12];
  3117. result.y = this.m[13];
  3118. result.z = this.m[14];
  3119. return this;
  3120. };
  3121. /**
  3122. * Remove rotation and scaling part from the Matrix.
  3123. * Returns the updated Matrix.
  3124. */
  3125. Matrix.prototype.removeRotationAndScaling = function () {
  3126. this.setRowFromFloats(0, 1, 0, 0, 0);
  3127. this.setRowFromFloats(1, 0, 1, 0, 0);
  3128. this.setRowFromFloats(2, 0, 0, 1, 0);
  3129. return this;
  3130. };
  3131. /**
  3132. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  3133. */
  3134. Matrix.prototype.multiply = function (other) {
  3135. var result = new Matrix();
  3136. this.multiplyToRef(other, result);
  3137. return result;
  3138. };
  3139. /**
  3140. * Updates the current Matrix from the passed one values.
  3141. * Returns the updated Matrix.
  3142. */
  3143. Matrix.prototype.copyFrom = function (other) {
  3144. for (var index = 0; index < 16; index++) {
  3145. this.m[index] = other.m[index];
  3146. }
  3147. this._markAsUpdated();
  3148. return this;
  3149. };
  3150. /**
  3151. * Populates the passed array from the starting index with the Matrix values.
  3152. * Returns the Matrix.
  3153. */
  3154. Matrix.prototype.copyToArray = function (array, offset) {
  3155. if (offset === void 0) { offset = 0; }
  3156. for (var index = 0; index < 16; index++) {
  3157. array[offset + index] = this.m[index];
  3158. }
  3159. return this;
  3160. };
  3161. /**
  3162. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  3163. */
  3164. Matrix.prototype.multiplyToRef = function (other, result) {
  3165. this.multiplyToArray(other, result.m, 0);
  3166. result._markAsUpdated();
  3167. return this;
  3168. };
  3169. /**
  3170. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  3171. */
  3172. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  3173. var tm0 = this.m[0];
  3174. var tm1 = this.m[1];
  3175. var tm2 = this.m[2];
  3176. var tm3 = this.m[3];
  3177. var tm4 = this.m[4];
  3178. var tm5 = this.m[5];
  3179. var tm6 = this.m[6];
  3180. var tm7 = this.m[7];
  3181. var tm8 = this.m[8];
  3182. var tm9 = this.m[9];
  3183. var tm10 = this.m[10];
  3184. var tm11 = this.m[11];
  3185. var tm12 = this.m[12];
  3186. var tm13 = this.m[13];
  3187. var tm14 = this.m[14];
  3188. var tm15 = this.m[15];
  3189. var om0 = other.m[0];
  3190. var om1 = other.m[1];
  3191. var om2 = other.m[2];
  3192. var om3 = other.m[3];
  3193. var om4 = other.m[4];
  3194. var om5 = other.m[5];
  3195. var om6 = other.m[6];
  3196. var om7 = other.m[7];
  3197. var om8 = other.m[8];
  3198. var om9 = other.m[9];
  3199. var om10 = other.m[10];
  3200. var om11 = other.m[11];
  3201. var om12 = other.m[12];
  3202. var om13 = other.m[13];
  3203. var om14 = other.m[14];
  3204. var om15 = other.m[15];
  3205. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  3206. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  3207. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  3208. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  3209. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  3210. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  3211. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  3212. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  3213. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  3214. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  3215. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  3216. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  3217. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  3218. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  3219. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  3220. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  3221. return this;
  3222. };
  3223. /**
  3224. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  3225. */
  3226. Matrix.prototype.equals = function (value) {
  3227. return value &&
  3228. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  3229. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  3230. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  3231. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  3232. };
  3233. /**
  3234. * Returns a new Matrix from the current Matrix.
  3235. */
  3236. Matrix.prototype.clone = function () {
  3237. 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]);
  3238. };
  3239. /**
  3240. * Returns the string "Matrix"
  3241. */
  3242. Matrix.prototype.getClassName = function () {
  3243. return "Matrix";
  3244. };
  3245. /**
  3246. * Returns the Matrix hash code.
  3247. */
  3248. Matrix.prototype.getHashCode = function () {
  3249. var hash = this.m[0] || 0;
  3250. for (var i = 1; i < 16; i++) {
  3251. hash = (hash * 397) ^ (this.m[i] || 0);
  3252. }
  3253. return hash;
  3254. };
  3255. /**
  3256. * Decomposes the current Matrix into :
  3257. * - a scale vector3 passed as a reference to update,
  3258. * - a rotation quaternion passed as a reference to update,
  3259. * - a translation vector3 passed as a reference to update.
  3260. * Returns the boolean `true`.
  3261. */
  3262. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3263. translation.x = this.m[12];
  3264. translation.y = this.m[13];
  3265. translation.z = this.m[14];
  3266. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3267. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3268. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3269. if (this.determinant() <= 0) {
  3270. scale.y *= -1;
  3271. }
  3272. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3273. rotation.x = 0;
  3274. rotation.y = 0;
  3275. rotation.z = 0;
  3276. rotation.w = 1;
  3277. return false;
  3278. }
  3279. 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]);
  3280. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3281. return true;
  3282. };
  3283. /**
  3284. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3285. */
  3286. Matrix.prototype.getRotationMatrix = function () {
  3287. var result = Matrix.Identity();
  3288. this.getRotationMatrixToRef(result);
  3289. return result;
  3290. };
  3291. /**
  3292. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3293. * Returns the current Matrix.
  3294. */
  3295. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3296. var m = this.m;
  3297. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3298. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3299. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3300. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3301. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3302. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3303. 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);
  3304. return this;
  3305. };
  3306. // Statics
  3307. /**
  3308. * Returns a new Matrix set from the starting index of the passed array.
  3309. */
  3310. Matrix.FromArray = function (array, offset) {
  3311. var result = new Matrix();
  3312. if (!offset) {
  3313. offset = 0;
  3314. }
  3315. Matrix.FromArrayToRef(array, offset, result);
  3316. return result;
  3317. };
  3318. /**
  3319. * Sets the passed "result" matrix from the starting index of the passed array.
  3320. */
  3321. Matrix.FromArrayToRef = function (array, offset, result) {
  3322. for (var index = 0; index < 16; index++) {
  3323. result.m[index] = array[index + offset];
  3324. }
  3325. result._markAsUpdated();
  3326. };
  3327. /**
  3328. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3329. */
  3330. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3331. for (var index = 0; index < 16; index++) {
  3332. result.m[index] = array[index + offset] * scale;
  3333. }
  3334. result._markAsUpdated();
  3335. };
  3336. /**
  3337. * Sets the passed matrix "result" with the 16 passed floats.
  3338. */
  3339. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3340. result.m[0] = initialM11;
  3341. result.m[1] = initialM12;
  3342. result.m[2] = initialM13;
  3343. result.m[3] = initialM14;
  3344. result.m[4] = initialM21;
  3345. result.m[5] = initialM22;
  3346. result.m[6] = initialM23;
  3347. result.m[7] = initialM24;
  3348. result.m[8] = initialM31;
  3349. result.m[9] = initialM32;
  3350. result.m[10] = initialM33;
  3351. result.m[11] = initialM34;
  3352. result.m[12] = initialM41;
  3353. result.m[13] = initialM42;
  3354. result.m[14] = initialM43;
  3355. result.m[15] = initialM44;
  3356. result._markAsUpdated();
  3357. };
  3358. /**
  3359. * Returns the index-th row of the current matrix as a new Vector4.
  3360. */
  3361. Matrix.prototype.getRow = function (index) {
  3362. if (index < 0 || index > 3) {
  3363. return null;
  3364. }
  3365. var i = index * 4;
  3366. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3367. };
  3368. /**
  3369. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3370. * Returns the updated Matrix.
  3371. */
  3372. Matrix.prototype.setRow = function (index, row) {
  3373. if (index < 0 || index > 3) {
  3374. return this;
  3375. }
  3376. var i = index * 4;
  3377. this.m[i + 0] = row.x;
  3378. this.m[i + 1] = row.y;
  3379. this.m[i + 2] = row.z;
  3380. this.m[i + 3] = row.w;
  3381. this._markAsUpdated();
  3382. return this;
  3383. };
  3384. /**
  3385. * Compute the transpose of the matrix.
  3386. * Returns a new Matrix.
  3387. */
  3388. Matrix.prototype.transpose = function () {
  3389. return Matrix.Transpose(this);
  3390. };
  3391. /**
  3392. * Compute the transpose of the matrix.
  3393. * Returns the current matrix.
  3394. */
  3395. Matrix.prototype.transposeToRef = function (result) {
  3396. Matrix.TransposeToRef(this, result);
  3397. return this;
  3398. };
  3399. /**
  3400. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3401. * Returns the updated Matrix.
  3402. */
  3403. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3404. if (index < 0 || index > 3) {
  3405. return this;
  3406. }
  3407. var i = index * 4;
  3408. this.m[i + 0] = x;
  3409. this.m[i + 1] = y;
  3410. this.m[i + 2] = z;
  3411. this.m[i + 3] = w;
  3412. this._markAsUpdated();
  3413. return this;
  3414. };
  3415. Object.defineProperty(Matrix, "IdentityReadOnly", {
  3416. /**
  3417. * Static identity matrix to be used as readonly matrix
  3418. * Must not be updated.
  3419. */
  3420. get: function () {
  3421. return Matrix._identityReadOnly;
  3422. },
  3423. enumerable: true,
  3424. configurable: true
  3425. });
  3426. /**
  3427. * Returns a new Matrix set from the 16 passed floats.
  3428. */
  3429. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3430. var result = new Matrix();
  3431. result.m[0] = initialM11;
  3432. result.m[1] = initialM12;
  3433. result.m[2] = initialM13;
  3434. result.m[3] = initialM14;
  3435. result.m[4] = initialM21;
  3436. result.m[5] = initialM22;
  3437. result.m[6] = initialM23;
  3438. result.m[7] = initialM24;
  3439. result.m[8] = initialM31;
  3440. result.m[9] = initialM32;
  3441. result.m[10] = initialM33;
  3442. result.m[11] = initialM34;
  3443. result.m[12] = initialM41;
  3444. result.m[13] = initialM42;
  3445. result.m[14] = initialM43;
  3446. result.m[15] = initialM44;
  3447. return result;
  3448. };
  3449. /**
  3450. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3451. */
  3452. Matrix.Compose = function (scale, rotation, translation) {
  3453. var result = Matrix.Identity();
  3454. Matrix.ComposeToRef(scale, rotation, translation, result);
  3455. return result;
  3456. };
  3457. /**
  3458. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3459. */
  3460. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3461. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3462. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3463. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3464. result.setTranslation(translation);
  3465. };
  3466. /**
  3467. * Returns a new indentity Matrix.
  3468. */
  3469. Matrix.Identity = function () {
  3470. 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);
  3471. };
  3472. /**
  3473. * Sets the passed "result" as an identity matrix.
  3474. */
  3475. Matrix.IdentityToRef = function (result) {
  3476. 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);
  3477. };
  3478. /**
  3479. * Returns a new zero Matrix.
  3480. */
  3481. Matrix.Zero = function () {
  3482. 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);
  3483. };
  3484. /**
  3485. * Returns a new rotation matrix for "angle" radians around the X axis.
  3486. */
  3487. Matrix.RotationX = function (angle) {
  3488. var result = new Matrix();
  3489. Matrix.RotationXToRef(angle, result);
  3490. return result;
  3491. };
  3492. /**
  3493. * Returns a new Matrix as the passed inverted one.
  3494. */
  3495. Matrix.Invert = function (source) {
  3496. var result = new Matrix();
  3497. source.invertToRef(result);
  3498. return result;
  3499. };
  3500. /**
  3501. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3502. */
  3503. Matrix.RotationXToRef = function (angle, result) {
  3504. var s = Math.sin(angle);
  3505. var c = Math.cos(angle);
  3506. result.m[0] = 1.0;
  3507. result.m[15] = 1.0;
  3508. result.m[5] = c;
  3509. result.m[10] = c;
  3510. result.m[9] = -s;
  3511. result.m[6] = s;
  3512. result.m[1] = 0.0;
  3513. result.m[2] = 0.0;
  3514. result.m[3] = 0.0;
  3515. result.m[4] = 0.0;
  3516. result.m[7] = 0.0;
  3517. result.m[8] = 0.0;
  3518. result.m[11] = 0.0;
  3519. result.m[12] = 0.0;
  3520. result.m[13] = 0.0;
  3521. result.m[14] = 0.0;
  3522. result._markAsUpdated();
  3523. };
  3524. /**
  3525. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3526. */
  3527. Matrix.RotationY = function (angle) {
  3528. var result = new Matrix();
  3529. Matrix.RotationYToRef(angle, result);
  3530. return result;
  3531. };
  3532. /**
  3533. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3534. */
  3535. Matrix.RotationYToRef = function (angle, result) {
  3536. var s = Math.sin(angle);
  3537. var c = Math.cos(angle);
  3538. result.m[5] = 1.0;
  3539. result.m[15] = 1.0;
  3540. result.m[0] = c;
  3541. result.m[2] = -s;
  3542. result.m[8] = s;
  3543. result.m[10] = c;
  3544. result.m[1] = 0.0;
  3545. result.m[3] = 0.0;
  3546. result.m[4] = 0.0;
  3547. result.m[6] = 0.0;
  3548. result.m[7] = 0.0;
  3549. result.m[9] = 0.0;
  3550. result.m[11] = 0.0;
  3551. result.m[12] = 0.0;
  3552. result.m[13] = 0.0;
  3553. result.m[14] = 0.0;
  3554. result._markAsUpdated();
  3555. };
  3556. /**
  3557. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3558. */
  3559. Matrix.RotationZ = function (angle) {
  3560. var result = new Matrix();
  3561. Matrix.RotationZToRef(angle, result);
  3562. return result;
  3563. };
  3564. /**
  3565. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3566. */
  3567. Matrix.RotationZToRef = function (angle, result) {
  3568. var s = Math.sin(angle);
  3569. var c = Math.cos(angle);
  3570. result.m[10] = 1.0;
  3571. result.m[15] = 1.0;
  3572. result.m[0] = c;
  3573. result.m[1] = s;
  3574. result.m[4] = -s;
  3575. result.m[5] = c;
  3576. result.m[2] = 0.0;
  3577. result.m[3] = 0.0;
  3578. result.m[6] = 0.0;
  3579. result.m[7] = 0.0;
  3580. result.m[8] = 0.0;
  3581. result.m[9] = 0.0;
  3582. result.m[11] = 0.0;
  3583. result.m[12] = 0.0;
  3584. result.m[13] = 0.0;
  3585. result.m[14] = 0.0;
  3586. result._markAsUpdated();
  3587. };
  3588. /**
  3589. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3590. */
  3591. Matrix.RotationAxis = function (axis, angle) {
  3592. var result = Matrix.Zero();
  3593. Matrix.RotationAxisToRef(axis, angle, result);
  3594. return result;
  3595. };
  3596. /**
  3597. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3598. */
  3599. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3600. var s = Math.sin(-angle);
  3601. var c = Math.cos(-angle);
  3602. var c1 = 1 - c;
  3603. axis.normalize();
  3604. result.m[0] = (axis.x * axis.x) * c1 + c;
  3605. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3606. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3607. result.m[3] = 0.0;
  3608. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3609. result.m[5] = (axis.y * axis.y) * c1 + c;
  3610. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3611. result.m[7] = 0.0;
  3612. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3613. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3614. result.m[10] = (axis.z * axis.z) * c1 + c;
  3615. result.m[11] = 0.0;
  3616. result.m[15] = 1.0;
  3617. result._markAsUpdated();
  3618. };
  3619. /**
  3620. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3621. */
  3622. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3623. var result = new Matrix();
  3624. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3625. return result;
  3626. };
  3627. /**
  3628. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3629. */
  3630. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3631. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3632. this._tempQuaternion.toRotationMatrix(result);
  3633. };
  3634. /**
  3635. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3636. */
  3637. Matrix.Scaling = function (x, y, z) {
  3638. var result = Matrix.Zero();
  3639. Matrix.ScalingToRef(x, y, z, result);
  3640. return result;
  3641. };
  3642. /**
  3643. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3644. */
  3645. Matrix.ScalingToRef = function (x, y, z, result) {
  3646. result.m[0] = x;
  3647. result.m[1] = 0.0;
  3648. result.m[2] = 0.0;
  3649. result.m[3] = 0.0;
  3650. result.m[4] = 0.0;
  3651. result.m[5] = y;
  3652. result.m[6] = 0.0;
  3653. result.m[7] = 0.0;
  3654. result.m[8] = 0.0;
  3655. result.m[9] = 0.0;
  3656. result.m[10] = z;
  3657. result.m[11] = 0.0;
  3658. result.m[12] = 0.0;
  3659. result.m[13] = 0.0;
  3660. result.m[14] = 0.0;
  3661. result.m[15] = 1.0;
  3662. result._markAsUpdated();
  3663. };
  3664. /**
  3665. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3666. */
  3667. Matrix.Translation = function (x, y, z) {
  3668. var result = Matrix.Identity();
  3669. Matrix.TranslationToRef(x, y, z, result);
  3670. return result;
  3671. };
  3672. /**
  3673. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3674. */
  3675. Matrix.TranslationToRef = function (x, y, z, result) {
  3676. 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);
  3677. };
  3678. /**
  3679. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3680. */
  3681. Matrix.Lerp = function (startValue, endValue, gradient) {
  3682. var result = Matrix.Zero();
  3683. for (var index = 0; index < 16; index++) {
  3684. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3685. }
  3686. result._markAsUpdated();
  3687. return result;
  3688. };
  3689. /**
  3690. * Returns a new Matrix whose values are computed by :
  3691. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3692. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3693. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3694. */
  3695. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3696. var startScale = new Vector3(0, 0, 0);
  3697. var startRotation = new Quaternion();
  3698. var startTranslation = new Vector3(0, 0, 0);
  3699. startValue.decompose(startScale, startRotation, startTranslation);
  3700. var endScale = new Vector3(0, 0, 0);
  3701. var endRotation = new Quaternion();
  3702. var endTranslation = new Vector3(0, 0, 0);
  3703. endValue.decompose(endScale, endRotation, endTranslation);
  3704. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3705. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3706. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3707. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3708. };
  3709. /**
  3710. * 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".
  3711. * This methods works for a Left-Handed system.
  3712. */
  3713. Matrix.LookAtLH = function (eye, target, up) {
  3714. var result = Matrix.Zero();
  3715. Matrix.LookAtLHToRef(eye, target, up, result);
  3716. return result;
  3717. };
  3718. /**
  3719. * 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".
  3720. * This methods works for a Left-Handed system.
  3721. */
  3722. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3723. // Z axis
  3724. target.subtractToRef(eye, this._zAxis);
  3725. this._zAxis.normalize();
  3726. // X axis
  3727. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3728. if (this._xAxis.lengthSquared() === 0) {
  3729. this._xAxis.x = 1.0;
  3730. }
  3731. else {
  3732. this._xAxis.normalize();
  3733. }
  3734. // Y axis
  3735. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3736. this._yAxis.normalize();
  3737. // Eye angles
  3738. var ex = -Vector3.Dot(this._xAxis, eye);
  3739. var ey = -Vector3.Dot(this._yAxis, eye);
  3740. var ez = -Vector3.Dot(this._zAxis, eye);
  3741. 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);
  3742. };
  3743. /**
  3744. * 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".
  3745. * This methods works for a Right-Handed system.
  3746. */
  3747. Matrix.LookAtRH = function (eye, target, up) {
  3748. var result = Matrix.Zero();
  3749. Matrix.LookAtRHToRef(eye, target, up, result);
  3750. return result;
  3751. };
  3752. /**
  3753. * 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".
  3754. * This methods works for a Left-Handed system.
  3755. */
  3756. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3757. // Z axis
  3758. eye.subtractToRef(target, this._zAxis);
  3759. this._zAxis.normalize();
  3760. // X axis
  3761. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3762. if (this._xAxis.lengthSquared() === 0) {
  3763. this._xAxis.x = 1.0;
  3764. }
  3765. else {
  3766. this._xAxis.normalize();
  3767. }
  3768. // Y axis
  3769. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3770. this._yAxis.normalize();
  3771. // Eye angles
  3772. var ex = -Vector3.Dot(this._xAxis, eye);
  3773. var ey = -Vector3.Dot(this._yAxis, eye);
  3774. var ez = -Vector3.Dot(this._zAxis, eye);
  3775. 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);
  3776. };
  3777. /**
  3778. * 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.
  3779. */
  3780. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3781. var matrix = Matrix.Zero();
  3782. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3783. return matrix;
  3784. };
  3785. /**
  3786. * 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.
  3787. */
  3788. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3789. var n = znear;
  3790. var f = zfar;
  3791. var a = 2.0 / width;
  3792. var b = 2.0 / height;
  3793. var c = 2.0 / (f - n);
  3794. var d = -(f + n) / (f - n);
  3795. 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);
  3796. };
  3797. /**
  3798. * 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.
  3799. */
  3800. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3801. var matrix = Matrix.Zero();
  3802. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3803. return matrix;
  3804. };
  3805. /**
  3806. * 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.
  3807. */
  3808. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3809. var n = znear;
  3810. var f = zfar;
  3811. var a = 2.0 / (right - left);
  3812. var b = 2.0 / (top - bottom);
  3813. var c = 2.0 / (f - n);
  3814. var d = -(f + n) / (f - n);
  3815. var i0 = (left + right) / (left - right);
  3816. var i1 = (top + bottom) / (bottom - top);
  3817. 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);
  3818. };
  3819. /**
  3820. * 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.
  3821. */
  3822. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3823. var matrix = Matrix.Zero();
  3824. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3825. return matrix;
  3826. };
  3827. /**
  3828. * 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.
  3829. */
  3830. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3831. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3832. result.m[10] *= -1.0;
  3833. };
  3834. /**
  3835. * 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.
  3836. */
  3837. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3838. var matrix = Matrix.Zero();
  3839. var n = znear;
  3840. var f = zfar;
  3841. var a = 2.0 * n / width;
  3842. var b = 2.0 * n / height;
  3843. var c = (f + n) / (f - n);
  3844. var d = -2.0 * f * n / (f - n);
  3845. 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);
  3846. return matrix;
  3847. };
  3848. /**
  3849. * 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.
  3850. */
  3851. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3852. var matrix = Matrix.Zero();
  3853. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3854. return matrix;
  3855. };
  3856. /**
  3857. * 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.
  3858. */
  3859. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3860. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3861. var n = znear;
  3862. var f = zfar;
  3863. var t = 1.0 / (Math.tan(fov * 0.5));
  3864. var a = isVerticalFovFixed ? (t / aspect) : t;
  3865. var b = isVerticalFovFixed ? t : (t * aspect);
  3866. var c = (f + n) / (f - n);
  3867. var d = -2.0 * f * n / (f - n);
  3868. 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);
  3869. };
  3870. /**
  3871. * 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.
  3872. */
  3873. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3874. var matrix = Matrix.Zero();
  3875. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3876. return matrix;
  3877. };
  3878. /**
  3879. * 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.
  3880. */
  3881. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3882. //alternatively this could be expressed as:
  3883. // m = PerspectiveFovLHToRef
  3884. // m[10] *= -1.0;
  3885. // m[11] *= -1.0;
  3886. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3887. var n = znear;
  3888. var f = zfar;
  3889. var t = 1.0 / (Math.tan(fov * 0.5));
  3890. var a = isVerticalFovFixed ? (t / aspect) : t;
  3891. var b = isVerticalFovFixed ? t : (t * aspect);
  3892. var c = -(f + n) / (f - n);
  3893. var d = -2 * f * n / (f - n);
  3894. 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);
  3895. };
  3896. /**
  3897. * 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.
  3898. */
  3899. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3900. if (rightHanded === void 0) { rightHanded = false; }
  3901. var rightHandedFactor = rightHanded ? -1 : 1;
  3902. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3903. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3904. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3905. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3906. var xScale = 2.0 / (leftTan + rightTan);
  3907. var yScale = 2.0 / (upTan + downTan);
  3908. result.m[0] = xScale;
  3909. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3910. result.m[5] = yScale;
  3911. result.m[6] = result.m[7] = 0.0;
  3912. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3913. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3914. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3915. result.m[10] = -zfar / (znear - zfar);
  3916. result.m[11] = 1.0 * rightHandedFactor;
  3917. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3918. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3919. // result.m[14] = (znear * zfar) / (znear - zfar);
  3920. result._markAsUpdated();
  3921. };
  3922. /**
  3923. * Returns the final transformation matrix : world * view * projection * viewport
  3924. */
  3925. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3926. var cw = viewport.width;
  3927. var ch = viewport.height;
  3928. var cx = viewport.x;
  3929. var cy = viewport.y;
  3930. 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);
  3931. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3932. };
  3933. /**
  3934. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3935. */
  3936. Matrix.GetAsMatrix2x2 = function (matrix) {
  3937. return new Float32Array([
  3938. matrix.m[0], matrix.m[1],
  3939. matrix.m[4], matrix.m[5]
  3940. ]);
  3941. };
  3942. /**
  3943. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3944. */
  3945. Matrix.GetAsMatrix3x3 = function (matrix) {
  3946. return new Float32Array([
  3947. matrix.m[0], matrix.m[1], matrix.m[2],
  3948. matrix.m[4], matrix.m[5], matrix.m[6],
  3949. matrix.m[8], matrix.m[9], matrix.m[10]
  3950. ]);
  3951. };
  3952. /**
  3953. * Compute the transpose of the passed Matrix.
  3954. * Returns a new Matrix.
  3955. */
  3956. Matrix.Transpose = function (matrix) {
  3957. var result = new Matrix();
  3958. Matrix.TransposeToRef(matrix, result);
  3959. return result;
  3960. };
  3961. /**
  3962. * Compute the transpose of the passed Matrix and store it in the result matrix.
  3963. */
  3964. Matrix.TransposeToRef = function (matrix, result) {
  3965. result.m[0] = matrix.m[0];
  3966. result.m[1] = matrix.m[4];
  3967. result.m[2] = matrix.m[8];
  3968. result.m[3] = matrix.m[12];
  3969. result.m[4] = matrix.m[1];
  3970. result.m[5] = matrix.m[5];
  3971. result.m[6] = matrix.m[9];
  3972. result.m[7] = matrix.m[13];
  3973. result.m[8] = matrix.m[2];
  3974. result.m[9] = matrix.m[6];
  3975. result.m[10] = matrix.m[10];
  3976. result.m[11] = matrix.m[14];
  3977. result.m[12] = matrix.m[3];
  3978. result.m[13] = matrix.m[7];
  3979. result.m[14] = matrix.m[11];
  3980. result.m[15] = matrix.m[15];
  3981. };
  3982. /**
  3983. * Returns a new Matrix as the reflection matrix across the passed plane.
  3984. */
  3985. Matrix.Reflection = function (plane) {
  3986. var matrix = new Matrix();
  3987. Matrix.ReflectionToRef(plane, matrix);
  3988. return matrix;
  3989. };
  3990. /**
  3991. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3992. */
  3993. Matrix.ReflectionToRef = function (plane, result) {
  3994. plane.normalize();
  3995. var x = plane.normal.x;
  3996. var y = plane.normal.y;
  3997. var z = plane.normal.z;
  3998. var temp = -2 * x;
  3999. var temp2 = -2 * y;
  4000. var temp3 = -2 * z;
  4001. result.m[0] = (temp * x) + 1;
  4002. result.m[1] = temp2 * x;
  4003. result.m[2] = temp3 * x;
  4004. result.m[3] = 0.0;
  4005. result.m[4] = temp * y;
  4006. result.m[5] = (temp2 * y) + 1;
  4007. result.m[6] = temp3 * y;
  4008. result.m[7] = 0.0;
  4009. result.m[8] = temp * z;
  4010. result.m[9] = temp2 * z;
  4011. result.m[10] = (temp3 * z) + 1;
  4012. result.m[11] = 0.0;
  4013. result.m[12] = temp * plane.d;
  4014. result.m[13] = temp2 * plane.d;
  4015. result.m[14] = temp3 * plane.d;
  4016. result.m[15] = 1.0;
  4017. result._markAsUpdated();
  4018. };
  4019. /**
  4020. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  4021. */
  4022. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  4023. result.m[0] = xaxis.x;
  4024. result.m[1] = xaxis.y;
  4025. result.m[2] = xaxis.z;
  4026. result.m[3] = 0.0;
  4027. result.m[4] = yaxis.x;
  4028. result.m[5] = yaxis.y;
  4029. result.m[6] = yaxis.z;
  4030. result.m[7] = 0.0;
  4031. result.m[8] = zaxis.x;
  4032. result.m[9] = zaxis.y;
  4033. result.m[10] = zaxis.z;
  4034. result.m[11] = 0.0;
  4035. result.m[12] = 0.0;
  4036. result.m[13] = 0.0;
  4037. result.m[14] = 0.0;
  4038. result.m[15] = 1.0;
  4039. result._markAsUpdated();
  4040. };
  4041. /**
  4042. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  4043. */
  4044. Matrix.FromQuaternionToRef = function (quat, result) {
  4045. var xx = quat.x * quat.x;
  4046. var yy = quat.y * quat.y;
  4047. var zz = quat.z * quat.z;
  4048. var xy = quat.x * quat.y;
  4049. var zw = quat.z * quat.w;
  4050. var zx = quat.z * quat.x;
  4051. var yw = quat.y * quat.w;
  4052. var yz = quat.y * quat.z;
  4053. var xw = quat.x * quat.w;
  4054. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4055. result.m[1] = 2.0 * (xy + zw);
  4056. result.m[2] = 2.0 * (zx - yw);
  4057. result.m[3] = 0.0;
  4058. result.m[4] = 2.0 * (xy - zw);
  4059. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4060. result.m[6] = 2.0 * (yz + xw);
  4061. result.m[7] = 0.0;
  4062. result.m[8] = 2.0 * (zx + yw);
  4063. result.m[9] = 2.0 * (yz - xw);
  4064. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4065. result.m[11] = 0.0;
  4066. result.m[12] = 0.0;
  4067. result.m[13] = 0.0;
  4068. result.m[14] = 0.0;
  4069. result.m[15] = 1.0;
  4070. result._markAsUpdated();
  4071. };
  4072. Matrix._tempQuaternion = new Quaternion();
  4073. Matrix._xAxis = Vector3.Zero();
  4074. Matrix._yAxis = Vector3.Zero();
  4075. Matrix._zAxis = Vector3.Zero();
  4076. Matrix._updateFlagSeed = 0;
  4077. Matrix._identityReadOnly = Matrix.Identity();
  4078. return Matrix;
  4079. }());
  4080. BABYLON.Matrix = Matrix;
  4081. var Plane = /** @class */ (function () {
  4082. /**
  4083. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  4084. */
  4085. function Plane(a, b, c, d) {
  4086. this.normal = new Vector3(a, b, c);
  4087. this.d = d;
  4088. }
  4089. /**
  4090. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  4091. */
  4092. Plane.prototype.asArray = function () {
  4093. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  4094. };
  4095. // Methods
  4096. /**
  4097. * Returns a new plane copied from the current Plane.
  4098. */
  4099. Plane.prototype.clone = function () {
  4100. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  4101. };
  4102. /**
  4103. * Returns the string "Plane".
  4104. */
  4105. Plane.prototype.getClassName = function () {
  4106. return "Plane";
  4107. };
  4108. /**
  4109. * Returns the Plane hash code.
  4110. */
  4111. Plane.prototype.getHashCode = function () {
  4112. var hash = this.normal.getHashCode();
  4113. hash = (hash * 397) ^ (this.d || 0);
  4114. return hash;
  4115. };
  4116. /**
  4117. * Normalize the current Plane in place.
  4118. * Returns the updated Plane.
  4119. */
  4120. Plane.prototype.normalize = function () {
  4121. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  4122. var magnitude = 0.0;
  4123. if (norm !== 0) {
  4124. magnitude = 1.0 / norm;
  4125. }
  4126. this.normal.x *= magnitude;
  4127. this.normal.y *= magnitude;
  4128. this.normal.z *= magnitude;
  4129. this.d *= magnitude;
  4130. return this;
  4131. };
  4132. /**
  4133. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  4134. */
  4135. Plane.prototype.transform = function (transformation) {
  4136. var transposedMatrix = Matrix.Transpose(transformation);
  4137. var x = this.normal.x;
  4138. var y = this.normal.y;
  4139. var z = this.normal.z;
  4140. var d = this.d;
  4141. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  4142. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  4143. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  4144. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  4145. return new Plane(normalX, normalY, normalZ, finalD);
  4146. };
  4147. /**
  4148. * Returns the dot product (float) of the point coordinates and the plane normal.
  4149. */
  4150. Plane.prototype.dotCoordinate = function (point) {
  4151. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  4152. };
  4153. /**
  4154. * Updates the current Plane from the plane defined by the three passed points.
  4155. * Returns the updated Plane.
  4156. */
  4157. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  4158. var x1 = point2.x - point1.x;
  4159. var y1 = point2.y - point1.y;
  4160. var z1 = point2.z - point1.z;
  4161. var x2 = point3.x - point1.x;
  4162. var y2 = point3.y - point1.y;
  4163. var z2 = point3.z - point1.z;
  4164. var yz = (y1 * z2) - (z1 * y2);
  4165. var xz = (z1 * x2) - (x1 * z2);
  4166. var xy = (x1 * y2) - (y1 * x2);
  4167. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  4168. var invPyth;
  4169. if (pyth !== 0) {
  4170. invPyth = 1.0 / pyth;
  4171. }
  4172. else {
  4173. invPyth = 0.0;
  4174. }
  4175. this.normal.x = yz * invPyth;
  4176. this.normal.y = xz * invPyth;
  4177. this.normal.z = xy * invPyth;
  4178. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  4179. return this;
  4180. };
  4181. /**
  4182. * Boolean : True is the vector "direction" is the same side than the plane normal.
  4183. */
  4184. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  4185. var dot = Vector3.Dot(this.normal, direction);
  4186. return (dot <= epsilon);
  4187. };
  4188. /**
  4189. * Returns the signed distance (float) from the passed point to the Plane.
  4190. */
  4191. Plane.prototype.signedDistanceTo = function (point) {
  4192. return Vector3.Dot(point, this.normal) + this.d;
  4193. };
  4194. // Statics
  4195. /**
  4196. * Returns a new Plane from the passed array.
  4197. */
  4198. Plane.FromArray = function (array) {
  4199. return new Plane(array[0], array[1], array[2], array[3]);
  4200. };
  4201. /**
  4202. * Returns a new Plane defined by the three passed points.
  4203. */
  4204. Plane.FromPoints = function (point1, point2, point3) {
  4205. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4206. result.copyFromPoints(point1, point2, point3);
  4207. return result;
  4208. };
  4209. /**
  4210. * Returns a new Plane the normal vector to this plane at the passed origin point.
  4211. * Note : the vector "normal" is updated because normalized.
  4212. */
  4213. Plane.FromPositionAndNormal = function (origin, normal) {
  4214. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4215. normal.normalize();
  4216. result.normal = normal;
  4217. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4218. return result;
  4219. };
  4220. /**
  4221. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  4222. */
  4223. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  4224. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4225. return Vector3.Dot(point, normal) + d;
  4226. };
  4227. return Plane;
  4228. }());
  4229. BABYLON.Plane = Plane;
  4230. var Viewport = /** @class */ (function () {
  4231. /**
  4232. * Creates a Viewport object located at (x, y) and sized (width, height).
  4233. */
  4234. function Viewport(x, y, width, height) {
  4235. this.x = x;
  4236. this.y = y;
  4237. this.width = width;
  4238. this.height = height;
  4239. }
  4240. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  4241. if (renderWidthOrEngine.getRenderWidth) {
  4242. var engine = renderWidthOrEngine;
  4243. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  4244. }
  4245. var renderWidth = renderWidthOrEngine;
  4246. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  4247. };
  4248. /**
  4249. * Returns a new Viewport copied from the current one.
  4250. */
  4251. Viewport.prototype.clone = function () {
  4252. return new Viewport(this.x, this.y, this.width, this.height);
  4253. };
  4254. return Viewport;
  4255. }());
  4256. BABYLON.Viewport = Viewport;
  4257. var Frustum = /** @class */ (function () {
  4258. function Frustum() {
  4259. }
  4260. /**
  4261. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  4262. */
  4263. Frustum.GetPlanes = function (transform) {
  4264. var frustumPlanes = [];
  4265. for (var index = 0; index < 6; index++) {
  4266. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  4267. }
  4268. Frustum.GetPlanesToRef(transform, frustumPlanes);
  4269. return frustumPlanes;
  4270. };
  4271. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  4272. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  4273. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  4274. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  4275. frustumPlane.d = transform.m[15] + transform.m[14];
  4276. frustumPlane.normalize();
  4277. };
  4278. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  4279. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  4280. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  4281. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  4282. frustumPlane.d = transform.m[15] - transform.m[14];
  4283. frustumPlane.normalize();
  4284. };
  4285. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  4286. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  4287. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  4288. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  4289. frustumPlane.d = transform.m[15] + transform.m[12];
  4290. frustumPlane.normalize();
  4291. };
  4292. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  4293. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  4294. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  4295. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  4296. frustumPlane.d = transform.m[15] - transform.m[12];
  4297. frustumPlane.normalize();
  4298. };
  4299. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  4300. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  4301. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  4302. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  4303. frustumPlane.d = transform.m[15] - transform.m[13];
  4304. frustumPlane.normalize();
  4305. };
  4306. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  4307. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  4308. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  4309. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  4310. frustumPlane.d = transform.m[15] + transform.m[13];
  4311. frustumPlane.normalize();
  4312. };
  4313. /**
  4314. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4315. */
  4316. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4317. // Near
  4318. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  4319. // Far
  4320. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  4321. // Left
  4322. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  4323. // Right
  4324. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  4325. // Top
  4326. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  4327. // Bottom
  4328. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  4329. };
  4330. return Frustum;
  4331. }());
  4332. BABYLON.Frustum = Frustum;
  4333. var Space;
  4334. (function (Space) {
  4335. Space[Space["LOCAL"] = 0] = "LOCAL";
  4336. Space[Space["WORLD"] = 1] = "WORLD";
  4337. Space[Space["BONE"] = 2] = "BONE";
  4338. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4339. var Axis = /** @class */ (function () {
  4340. function Axis() {
  4341. }
  4342. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4343. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4344. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4345. return Axis;
  4346. }());
  4347. BABYLON.Axis = Axis;
  4348. ;
  4349. var BezierCurve = /** @class */ (function () {
  4350. function BezierCurve() {
  4351. }
  4352. /**
  4353. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4354. */
  4355. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4356. // Extract X (which is equal to time here)
  4357. var f0 = 1 - 3 * x2 + 3 * x1;
  4358. var f1 = 3 * x2 - 6 * x1;
  4359. var f2 = 3 * x1;
  4360. var refinedT = t;
  4361. for (var i = 0; i < 5; i++) {
  4362. var refinedT2 = refinedT * refinedT;
  4363. var refinedT3 = refinedT2 * refinedT;
  4364. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4365. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4366. refinedT -= (x - t) * slope;
  4367. refinedT = Math.min(1, Math.max(0, refinedT));
  4368. }
  4369. // Resolve cubic bezier for the given x
  4370. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4371. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4372. Math.pow(refinedT, 3);
  4373. };
  4374. return BezierCurve;
  4375. }());
  4376. BABYLON.BezierCurve = BezierCurve;
  4377. var Orientation;
  4378. (function (Orientation) {
  4379. Orientation[Orientation["CW"] = 0] = "CW";
  4380. Orientation[Orientation["CCW"] = 1] = "CCW";
  4381. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4382. var Angle = /** @class */ (function () {
  4383. /**
  4384. * Creates an Angle object of "radians" radians (float).
  4385. */
  4386. function Angle(radians) {
  4387. var _this = this;
  4388. /**
  4389. * Returns the Angle value in degrees (float).
  4390. */
  4391. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4392. /**
  4393. * Returns the Angle value in radians (float).
  4394. */
  4395. this.radians = function () { return _this._radians; };
  4396. this._radians = radians;
  4397. if (this._radians < 0.0)
  4398. this._radians += (2.0 * Math.PI);
  4399. }
  4400. /**
  4401. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4402. */
  4403. Angle.BetweenTwoPoints = function (a, b) {
  4404. var delta = b.subtract(a);
  4405. var theta = Math.atan2(delta.y, delta.x);
  4406. return new Angle(theta);
  4407. };
  4408. /**
  4409. * Returns a new Angle object from the passed float in radians.
  4410. */
  4411. Angle.FromRadians = function (radians) {
  4412. return new Angle(radians);
  4413. };
  4414. /**
  4415. * Returns a new Angle object from the passed float in degrees.
  4416. */
  4417. Angle.FromDegrees = function (degrees) {
  4418. return new Angle(degrees * Math.PI / 180.0);
  4419. };
  4420. return Angle;
  4421. }());
  4422. BABYLON.Angle = Angle;
  4423. var Arc2 = /** @class */ (function () {
  4424. /**
  4425. * Creates an Arc object from the three passed points : start, middle and end.
  4426. */
  4427. function Arc2(startPoint, midPoint, endPoint) {
  4428. this.startPoint = startPoint;
  4429. this.midPoint = midPoint;
  4430. this.endPoint = endPoint;
  4431. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4432. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4433. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4434. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4435. 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);
  4436. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4437. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4438. var a1 = this.startAngle.degrees();
  4439. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4440. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4441. // angles correction
  4442. if (a2 - a1 > +180.0)
  4443. a2 -= 360.0;
  4444. if (a2 - a1 < -180.0)
  4445. a2 += 360.0;
  4446. if (a3 - a2 > +180.0)
  4447. a3 -= 360.0;
  4448. if (a3 - a2 < -180.0)
  4449. a3 += 360.0;
  4450. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4451. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4452. }
  4453. return Arc2;
  4454. }());
  4455. BABYLON.Arc2 = Arc2;
  4456. var Path2 = /** @class */ (function () {
  4457. /**
  4458. * Creates a Path2 object from the starting 2D coordinates x and y.
  4459. */
  4460. function Path2(x, y) {
  4461. this._points = new Array();
  4462. this._length = 0.0;
  4463. this.closed = false;
  4464. this._points.push(new Vector2(x, y));
  4465. }
  4466. /**
  4467. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4468. * Returns the updated Path2.
  4469. */
  4470. Path2.prototype.addLineTo = function (x, y) {
  4471. if (this.closed) {
  4472. //Tools.Error("cannot add lines to closed paths");
  4473. return this;
  4474. }
  4475. var newPoint = new Vector2(x, y);
  4476. var previousPoint = this._points[this._points.length - 1];
  4477. this._points.push(newPoint);
  4478. this._length += newPoint.subtract(previousPoint).length();
  4479. return this;
  4480. };
  4481. /**
  4482. * 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.
  4483. * Returns the updated Path2.
  4484. */
  4485. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4486. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4487. if (this.closed) {
  4488. //Tools.Error("cannot add arcs to closed paths");
  4489. return this;
  4490. }
  4491. var startPoint = this._points[this._points.length - 1];
  4492. var midPoint = new Vector2(midX, midY);
  4493. var endPoint = new Vector2(endX, endY);
  4494. var arc = new Arc2(startPoint, midPoint, endPoint);
  4495. var increment = arc.angle.radians() / numberOfSegments;
  4496. if (arc.orientation === Orientation.CW)
  4497. increment *= -1;
  4498. var currentAngle = arc.startAngle.radians() + increment;
  4499. for (var i = 0; i < numberOfSegments; i++) {
  4500. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4501. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4502. this.addLineTo(x, y);
  4503. currentAngle += increment;
  4504. }
  4505. return this;
  4506. };
  4507. /**
  4508. * Closes the Path2.
  4509. * Returns the Path2.
  4510. */
  4511. Path2.prototype.close = function () {
  4512. this.closed = true;
  4513. return this;
  4514. };
  4515. /**
  4516. * Returns the Path2 total length (float).
  4517. */
  4518. Path2.prototype.length = function () {
  4519. var result = this._length;
  4520. if (!this.closed) {
  4521. var lastPoint = this._points[this._points.length - 1];
  4522. var firstPoint = this._points[0];
  4523. result += (firstPoint.subtract(lastPoint).length());
  4524. }
  4525. return result;
  4526. };
  4527. /**
  4528. * Returns the Path2 internal array of points.
  4529. */
  4530. Path2.prototype.getPoints = function () {
  4531. return this._points;
  4532. };
  4533. /**
  4534. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4535. */
  4536. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4537. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4538. //Tools.Error("normalized length position should be between 0 and 1.");
  4539. return Vector2.Zero();
  4540. }
  4541. var lengthPosition = normalizedLengthPosition * this.length();
  4542. var previousOffset = 0;
  4543. for (var i = 0; i < this._points.length; i++) {
  4544. var j = (i + 1) % this._points.length;
  4545. var a = this._points[i];
  4546. var b = this._points[j];
  4547. var bToA = b.subtract(a);
  4548. var nextOffset = (bToA.length() + previousOffset);
  4549. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4550. var dir = bToA.normalize();
  4551. var localOffset = lengthPosition - previousOffset;
  4552. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4553. }
  4554. previousOffset = nextOffset;
  4555. }
  4556. //Tools.Error("internal error");
  4557. return Vector2.Zero();
  4558. };
  4559. /**
  4560. * Returns a new Path2 starting at the coordinates (x, y).
  4561. */
  4562. Path2.StartingAt = function (x, y) {
  4563. return new Path2(x, y);
  4564. };
  4565. return Path2;
  4566. }());
  4567. BABYLON.Path2 = Path2;
  4568. var Path3D = /** @class */ (function () {
  4569. /**
  4570. * new Path3D(path, normal, raw)
  4571. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4572. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4573. * path : an array of Vector3, the curve axis of the Path3D
  4574. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4575. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4576. */
  4577. function Path3D(path, firstNormal, raw) {
  4578. if (firstNormal === void 0) { firstNormal = null; }
  4579. this.path = path;
  4580. this._curve = new Array();
  4581. this._distances = new Array();
  4582. this._tangents = new Array();
  4583. this._normals = new Array();
  4584. this._binormals = new Array();
  4585. for (var p = 0; p < path.length; p++) {
  4586. this._curve[p] = path[p].clone(); // hard copy
  4587. }
  4588. this._raw = raw || false;
  4589. this._compute(firstNormal);
  4590. }
  4591. /**
  4592. * Returns the Path3D array of successive Vector3 designing its curve.
  4593. */
  4594. Path3D.prototype.getCurve = function () {
  4595. return this._curve;
  4596. };
  4597. /**
  4598. * Returns an array populated with tangent vectors on each Path3D curve point.
  4599. */
  4600. Path3D.prototype.getTangents = function () {
  4601. return this._tangents;
  4602. };
  4603. /**
  4604. * Returns an array populated with normal vectors on each Path3D curve point.
  4605. */
  4606. Path3D.prototype.getNormals = function () {
  4607. return this._normals;
  4608. };
  4609. /**
  4610. * Returns an array populated with binormal vectors on each Path3D curve point.
  4611. */
  4612. Path3D.prototype.getBinormals = function () {
  4613. return this._binormals;
  4614. };
  4615. /**
  4616. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4617. */
  4618. Path3D.prototype.getDistances = function () {
  4619. return this._distances;
  4620. };
  4621. /**
  4622. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4623. * Returns the same object updated.
  4624. */
  4625. Path3D.prototype.update = function (path, firstNormal) {
  4626. if (firstNormal === void 0) { firstNormal = null; }
  4627. for (var p = 0; p < path.length; p++) {
  4628. this._curve[p].x = path[p].x;
  4629. this._curve[p].y = path[p].y;
  4630. this._curve[p].z = path[p].z;
  4631. }
  4632. this._compute(firstNormal);
  4633. return this;
  4634. };
  4635. // private function compute() : computes tangents, normals and binormals
  4636. Path3D.prototype._compute = function (firstNormal) {
  4637. var l = this._curve.length;
  4638. // first and last tangents
  4639. this._tangents[0] = this._getFirstNonNullVector(0);
  4640. if (!this._raw) {
  4641. this._tangents[0].normalize();
  4642. }
  4643. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4644. if (!this._raw) {
  4645. this._tangents[l - 1].normalize();
  4646. }
  4647. // normals and binormals at first point : arbitrary vector with _normalVector()
  4648. var tg0 = this._tangents[0];
  4649. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4650. this._normals[0] = pp0;
  4651. if (!this._raw) {
  4652. this._normals[0].normalize();
  4653. }
  4654. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4655. if (!this._raw) {
  4656. this._binormals[0].normalize();
  4657. }
  4658. this._distances[0] = 0.0;
  4659. // normals and binormals : next points
  4660. var prev; // previous vector (segment)
  4661. var cur; // current vector (segment)
  4662. var curTang; // current tangent
  4663. // previous normal
  4664. var prevBinor; // previous binormal
  4665. for (var i = 1; i < l; i++) {
  4666. // tangents
  4667. prev = this._getLastNonNullVector(i);
  4668. if (i < l - 1) {
  4669. cur = this._getFirstNonNullVector(i);
  4670. this._tangents[i] = prev.add(cur);
  4671. this._tangents[i].normalize();
  4672. }
  4673. this._distances[i] = this._distances[i - 1] + prev.length();
  4674. // normals and binormals
  4675. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4676. curTang = this._tangents[i];
  4677. prevBinor = this._binormals[i - 1];
  4678. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4679. if (!this._raw) {
  4680. this._normals[i].normalize();
  4681. }
  4682. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4683. if (!this._raw) {
  4684. this._binormals[i].normalize();
  4685. }
  4686. }
  4687. };
  4688. // private function getFirstNonNullVector(index)
  4689. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4690. Path3D.prototype._getFirstNonNullVector = function (index) {
  4691. var i = 1;
  4692. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4693. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4694. i++;
  4695. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4696. }
  4697. return nNVector;
  4698. };
  4699. // private function getLastNonNullVector(index)
  4700. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4701. Path3D.prototype._getLastNonNullVector = function (index) {
  4702. var i = 1;
  4703. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4704. while (nLVector.length() === 0 && index > i + 1) {
  4705. i++;
  4706. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4707. }
  4708. return nLVector;
  4709. };
  4710. // private function normalVector(v0, vt, va) :
  4711. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4712. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4713. Path3D.prototype._normalVector = function (v0, vt, va) {
  4714. var normal0;
  4715. var tgl = vt.length();
  4716. if (tgl === 0.0) {
  4717. tgl = 1.0;
  4718. }
  4719. if (va === undefined || va === null) {
  4720. var point;
  4721. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4722. point = new Vector3(0.0, -1.0, 0.0);
  4723. }
  4724. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4725. point = new Vector3(1.0, 0.0, 0.0);
  4726. }
  4727. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4728. point = new Vector3(0.0, 0.0, 1.0);
  4729. }
  4730. else {
  4731. point = Vector3.Zero();
  4732. }
  4733. normal0 = Vector3.Cross(vt, point);
  4734. }
  4735. else {
  4736. normal0 = Vector3.Cross(vt, va);
  4737. Vector3.CrossToRef(normal0, vt, normal0);
  4738. }
  4739. normal0.normalize();
  4740. return normal0;
  4741. };
  4742. return Path3D;
  4743. }());
  4744. BABYLON.Path3D = Path3D;
  4745. var Curve3 = /** @class */ (function () {
  4746. /**
  4747. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4748. * A Curve3 is designed from a series of successive Vector3.
  4749. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4750. */
  4751. function Curve3(points) {
  4752. this._length = 0.0;
  4753. this._points = points;
  4754. this._length = this._computeLength(points);
  4755. }
  4756. /**
  4757. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4758. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4759. * @param v1 (Vector3) the control point
  4760. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4761. * @param nbPoints (integer) the wanted number of points in the curve
  4762. */
  4763. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4764. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4765. var bez = new Array();
  4766. var equation = function (t, val0, val1, val2) {
  4767. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4768. return res;
  4769. };
  4770. for (var i = 0; i <= nbPoints; i++) {
  4771. 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)));
  4772. }
  4773. return new Curve3(bez);
  4774. };
  4775. /**
  4776. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4777. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4778. * @param v1 (Vector3) the first control point
  4779. * @param v2 (Vector3) the second control point
  4780. * @param v3 (Vector3) the end point of the Cubic Bezier
  4781. * @param nbPoints (integer) the wanted number of points in the curve
  4782. */
  4783. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4784. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4785. var bez = new Array();
  4786. var equation = function (t, val0, val1, val2, val3) {
  4787. 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;
  4788. return res;
  4789. };
  4790. for (var i = 0; i <= nbPoints; i++) {
  4791. 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)));
  4792. }
  4793. return new Curve3(bez);
  4794. };
  4795. /**
  4796. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4797. * @param p1 (Vector3) the origin point of the Hermite Spline
  4798. * @param t1 (Vector3) the tangent vector at the origin point
  4799. * @param p2 (Vector3) the end point of the Hermite Spline
  4800. * @param t2 (Vector3) the tangent vector at the end point
  4801. * @param nbPoints (integer) the wanted number of points in the curve
  4802. */
  4803. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4804. var hermite = new Array();
  4805. var step = 1.0 / nbPoints;
  4806. for (var i = 0; i <= nbPoints; i++) {
  4807. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4808. }
  4809. return new Curve3(hermite);
  4810. };
  4811. /**
  4812. * Returns a Curve3 object along a CatmullRom Spline curve :
  4813. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4814. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4815. */
  4816. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4817. var totalPoints = new Array();
  4818. totalPoints.push(points[0].clone());
  4819. Array.prototype.push.apply(totalPoints, points);
  4820. totalPoints.push(points[points.length - 1].clone());
  4821. var catmullRom = new Array();
  4822. var step = 1.0 / nbPoints;
  4823. var amount = 0.0;
  4824. for (var i = 0; i < totalPoints.length - 3; i++) {
  4825. amount = 0;
  4826. for (var c = 0; c < nbPoints; c++) {
  4827. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4828. amount += step;
  4829. }
  4830. }
  4831. i--;
  4832. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4833. return new Curve3(catmullRom);
  4834. };
  4835. /**
  4836. * Returns the Curve3 stored array of successive Vector3
  4837. */
  4838. Curve3.prototype.getPoints = function () {
  4839. return this._points;
  4840. };
  4841. /**
  4842. * Returns the computed length (float) of the curve.
  4843. */
  4844. Curve3.prototype.length = function () {
  4845. return this._length;
  4846. };
  4847. /**
  4848. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4849. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4850. * curveA and curveB keep unchanged.
  4851. */
  4852. Curve3.prototype.continue = function (curve) {
  4853. var lastPoint = this._points[this._points.length - 1];
  4854. var continuedPoints = this._points.slice();
  4855. var curvePoints = curve.getPoints();
  4856. for (var i = 1; i < curvePoints.length; i++) {
  4857. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4858. }
  4859. var continuedCurve = new Curve3(continuedPoints);
  4860. return continuedCurve;
  4861. };
  4862. Curve3.prototype._computeLength = function (path) {
  4863. var l = 0;
  4864. for (var i = 1; i < path.length; i++) {
  4865. l += (path[i].subtract(path[i - 1])).length();
  4866. }
  4867. return l;
  4868. };
  4869. return Curve3;
  4870. }());
  4871. BABYLON.Curve3 = Curve3;
  4872. // Vertex formats
  4873. var PositionNormalVertex = /** @class */ (function () {
  4874. function PositionNormalVertex(position, normal) {
  4875. if (position === void 0) { position = Vector3.Zero(); }
  4876. if (normal === void 0) { normal = Vector3.Up(); }
  4877. this.position = position;
  4878. this.normal = normal;
  4879. }
  4880. PositionNormalVertex.prototype.clone = function () {
  4881. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4882. };
  4883. return PositionNormalVertex;
  4884. }());
  4885. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4886. var PositionNormalTextureVertex = /** @class */ (function () {
  4887. function PositionNormalTextureVertex(position, normal, uv) {
  4888. if (position === void 0) { position = Vector3.Zero(); }
  4889. if (normal === void 0) { normal = Vector3.Up(); }
  4890. if (uv === void 0) { uv = Vector2.Zero(); }
  4891. this.position = position;
  4892. this.normal = normal;
  4893. this.uv = uv;
  4894. }
  4895. PositionNormalTextureVertex.prototype.clone = function () {
  4896. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4897. };
  4898. return PositionNormalTextureVertex;
  4899. }());
  4900. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4901. // Temporary pre-allocated objects for engine internal use
  4902. // usage in any internal function :
  4903. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4904. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4905. var Tmp = /** @class */ (function () {
  4906. function Tmp() {
  4907. }
  4908. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4909. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4910. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4911. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4912. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4913. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4914. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4915. Matrix.Zero(), Matrix.Zero(),
  4916. Matrix.Zero(), Matrix.Zero(),
  4917. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4918. return Tmp;
  4919. }());
  4920. BABYLON.Tmp = Tmp;
  4921. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4922. var MathTmp = /** @class */ (function () {
  4923. function MathTmp() {
  4924. }
  4925. MathTmp.Vector3 = [Vector3.Zero()];
  4926. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4927. MathTmp.Quaternion = [Quaternion.Zero()];
  4928. return MathTmp;
  4929. }());
  4930. })(BABYLON || (BABYLON = {}));
  4931. //# sourceMappingURL=babylon.math.js.map
  4932. var BABYLON;
  4933. (function (BABYLON) {
  4934. var Scalar = /** @class */ (function () {
  4935. function Scalar() {
  4936. }
  4937. /**
  4938. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  4939. */
  4940. Scalar.WithinEpsilon = function (a, b, epsilon) {
  4941. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4942. var num = a - b;
  4943. return -epsilon <= num && num <= epsilon;
  4944. };
  4945. /**
  4946. * Returns a string : the upper case translation of the number i to hexadecimal.
  4947. */
  4948. Scalar.ToHex = function (i) {
  4949. var str = i.toString(16);
  4950. if (i <= 15) {
  4951. return ("0" + str).toUpperCase();
  4952. }
  4953. return str.toUpperCase();
  4954. };
  4955. /**
  4956. * Returns -1 if value is negative and +1 is value is positive.
  4957. * Returns the value itself if it's equal to zero.
  4958. */
  4959. Scalar.Sign = function (value) {
  4960. value = +value; // convert to a number
  4961. if (value === 0 || isNaN(value))
  4962. return value;
  4963. return value > 0 ? 1 : -1;
  4964. };
  4965. /**
  4966. * Returns the value itself if it's between min and max.
  4967. * Returns min if the value is lower than min.
  4968. * Returns max if the value is greater than max.
  4969. */
  4970. Scalar.Clamp = function (value, min, max) {
  4971. if (min === void 0) { min = 0; }
  4972. if (max === void 0) { max = 1; }
  4973. return Math.min(max, Math.max(min, value));
  4974. };
  4975. /**
  4976. * Returns the log2 of value.
  4977. */
  4978. Scalar.Log2 = function (value) {
  4979. return Math.log(value) * Math.LOG2E;
  4980. };
  4981. /**
  4982. * Loops the value, so that it is never larger than length and never smaller than 0.
  4983. *
  4984. * This is similar to the modulo operator but it works with floating point numbers.
  4985. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  4986. * With t = 5 and length = 2.5, the result would be 0.0.
  4987. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  4988. */
  4989. Scalar.Repeat = function (value, length) {
  4990. return value - Math.floor(value / length) * length;
  4991. };
  4992. /**
  4993. * Normalize the value between 0.0 and 1.0 using min and max values
  4994. */
  4995. Scalar.Normalize = function (value, min, max) {
  4996. return (value - min) / (max - min);
  4997. };
  4998. /**
  4999. * Denormalize the value from 0.0 and 1.0 using min and max values
  5000. */
  5001. Scalar.Denormalize = function (normalized, min, max) {
  5002. return (normalized * (max - min) + min);
  5003. };
  5004. /**
  5005. * Calculates the shortest difference between two given angles given in degrees.
  5006. */
  5007. Scalar.DeltaAngle = function (current, target) {
  5008. var num = Scalar.Repeat(target - current, 360.0);
  5009. if (num > 180.0) {
  5010. num -= 360.0;
  5011. }
  5012. return num;
  5013. };
  5014. /**
  5015. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  5016. *
  5017. * The returned value will move back and forth between 0 and length
  5018. */
  5019. Scalar.PingPong = function (tx, length) {
  5020. var t = Scalar.Repeat(tx, length * 2.0);
  5021. return length - Math.abs(t - length);
  5022. };
  5023. /**
  5024. * Interpolates between min and max with smoothing at the limits.
  5025. *
  5026. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  5027. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  5028. */
  5029. Scalar.SmoothStep = function (from, to, tx) {
  5030. var t = Scalar.Clamp(tx);
  5031. t = -2.0 * t * t * t + 3.0 * t * t;
  5032. return to * t + from * (1.0 - t);
  5033. };
  5034. /**
  5035. * Moves a value current towards target.
  5036. *
  5037. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  5038. * Negative values of maxDelta pushes the value away from target.
  5039. */
  5040. Scalar.MoveTowards = function (current, target, maxDelta) {
  5041. var result = 0;
  5042. if (Math.abs(target - current) <= maxDelta) {
  5043. result = target;
  5044. }
  5045. else {
  5046. result = current + Scalar.Sign(target - current) * maxDelta;
  5047. }
  5048. return result;
  5049. };
  5050. /**
  5051. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5052. *
  5053. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  5054. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  5055. */
  5056. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  5057. var num = Scalar.DeltaAngle(current, target);
  5058. var result = 0;
  5059. if (-maxDelta < num && num < maxDelta) {
  5060. result = target;
  5061. }
  5062. else {
  5063. target = current + num;
  5064. result = Scalar.MoveTowards(current, target, maxDelta);
  5065. }
  5066. return result;
  5067. };
  5068. /**
  5069. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  5070. */
  5071. Scalar.Lerp = function (start, end, amount) {
  5072. return start + ((end - start) * amount);
  5073. };
  5074. /**
  5075. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5076. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  5077. */
  5078. Scalar.LerpAngle = function (start, end, amount) {
  5079. var num = Scalar.Repeat(end - start, 360.0);
  5080. if (num > 180.0) {
  5081. num -= 360.0;
  5082. }
  5083. return start + num * Scalar.Clamp(amount);
  5084. };
  5085. /**
  5086. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  5087. */
  5088. Scalar.InverseLerp = function (a, b, value) {
  5089. var result = 0;
  5090. if (a != b) {
  5091. result = Scalar.Clamp((value - a) / (b - a));
  5092. }
  5093. else {
  5094. result = 0.0;
  5095. }
  5096. return result;
  5097. };
  5098. /**
  5099. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  5100. */
  5101. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5102. var squared = amount * amount;
  5103. var cubed = amount * squared;
  5104. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5105. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5106. var part3 = (cubed - (2.0 * squared)) + amount;
  5107. var part4 = cubed - squared;
  5108. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  5109. };
  5110. /**
  5111. * Returns a random float number between and min and max values
  5112. */
  5113. Scalar.RandomRange = function (min, max) {
  5114. if (min === max)
  5115. return min;
  5116. return ((Math.random() * (max - min)) + min);
  5117. };
  5118. /**
  5119. * This function returns percentage of a number in a given range.
  5120. *
  5121. * RangeToPercent(40,20,60) will return 0.5 (50%)
  5122. * RangeToPercent(34,0,100) will return 0.34 (34%)
  5123. */
  5124. Scalar.RangeToPercent = function (number, min, max) {
  5125. return ((number - min) / (max - min));
  5126. };
  5127. /**
  5128. * This function returns number that corresponds to the percentage in a given range.
  5129. *
  5130. * PercentToRange(0.34,0,100) will return 34.
  5131. */
  5132. Scalar.PercentToRange = function (percent, min, max) {
  5133. return ((max - min) * percent + min);
  5134. };
  5135. /**
  5136. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  5137. * @param angle The angle to normalize in radian.
  5138. * @return The converted angle.
  5139. */
  5140. Scalar.NormalizeRadians = function (angle) {
  5141. // More precise but slower version kept for reference.
  5142. // angle = angle % Tools.TwoPi;
  5143. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  5144. //if (angle > Math.PI) {
  5145. // angle -= Tools.TwoPi;
  5146. //}
  5147. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  5148. return angle;
  5149. };
  5150. /**
  5151. * Two pi constants convenient for computation.
  5152. */
  5153. Scalar.TwoPi = Math.PI * 2;
  5154. return Scalar;
  5155. }());
  5156. BABYLON.Scalar = Scalar;
  5157. })(BABYLON || (BABYLON = {}));
  5158. //# sourceMappingURL=babylon.math.scalar.js.map
  5159. //# sourceMappingURL=babylon.mixins.js.map
  5160. var BABYLON;
  5161. (function (BABYLON) {
  5162. var __decoratorInitialStore = {};
  5163. var __mergedStore = {};
  5164. var _copySource = function (creationFunction, source, instanciate) {
  5165. var destination = creationFunction();
  5166. // Tags
  5167. if (BABYLON.Tags) {
  5168. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5169. }
  5170. var classStore = getMergedStore(destination);
  5171. // Properties
  5172. for (var property in classStore) {
  5173. var propertyDescriptor = classStore[property];
  5174. var sourceProperty = source[property];
  5175. var propertyType = propertyDescriptor.type;
  5176. if (sourceProperty !== undefined && sourceProperty !== null) {
  5177. switch (propertyType) {
  5178. case 0: // Value
  5179. case 6:// Mesh reference
  5180. destination[property] = sourceProperty;
  5181. break;
  5182. case 1:// Texture
  5183. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  5184. break;
  5185. case 2: // Color3
  5186. case 3: // FresnelParameters
  5187. case 4: // Vector2
  5188. case 5: // Vector3
  5189. case 7: // Color Curves
  5190. case 10:// Quaternion
  5191. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  5192. break;
  5193. }
  5194. }
  5195. }
  5196. return destination;
  5197. };
  5198. function getDirectStore(target) {
  5199. var classKey = target.getClassName();
  5200. if (!__decoratorInitialStore[classKey]) {
  5201. __decoratorInitialStore[classKey] = {};
  5202. }
  5203. return __decoratorInitialStore[classKey];
  5204. }
  5205. /**
  5206. * Return the list of properties flagged as serializable
  5207. * @param target: host object
  5208. */
  5209. function getMergedStore(target) {
  5210. var classKey = target.getClassName();
  5211. if (__mergedStore[classKey]) {
  5212. return __mergedStore[classKey];
  5213. }
  5214. __mergedStore[classKey] = {};
  5215. var store = __mergedStore[classKey];
  5216. var currentTarget = target;
  5217. var currentKey = classKey;
  5218. while (currentKey) {
  5219. var initialStore = __decoratorInitialStore[currentKey];
  5220. for (var property in initialStore) {
  5221. store[property] = initialStore[property];
  5222. }
  5223. var parent_1 = void 0;
  5224. var done = false;
  5225. do {
  5226. parent_1 = Object.getPrototypeOf(currentTarget);
  5227. if (!parent_1.getClassName) {
  5228. done = true;
  5229. break;
  5230. }
  5231. if (parent_1.getClassName() !== currentKey) {
  5232. break;
  5233. }
  5234. currentTarget = parent_1;
  5235. } while (parent_1);
  5236. if (done) {
  5237. break;
  5238. }
  5239. currentKey = parent_1.getClassName();
  5240. currentTarget = parent_1;
  5241. }
  5242. return store;
  5243. }
  5244. function generateSerializableMember(type, sourceName) {
  5245. return function (target, propertyKey) {
  5246. var classStore = getDirectStore(target);
  5247. if (!classStore[propertyKey]) {
  5248. classStore[propertyKey] = { type: type, sourceName: sourceName };
  5249. }
  5250. };
  5251. }
  5252. function generateExpandMember(setCallback, targetKey) {
  5253. if (targetKey === void 0) { targetKey = null; }
  5254. return function (target, propertyKey) {
  5255. var key = targetKey || ("_" + propertyKey);
  5256. Object.defineProperty(target, propertyKey, {
  5257. get: function () {
  5258. return this[key];
  5259. },
  5260. set: function (value) {
  5261. if (this[key] === value) {
  5262. return;
  5263. }
  5264. this[key] = value;
  5265. target[setCallback].apply(this);
  5266. },
  5267. enumerable: true,
  5268. configurable: true
  5269. });
  5270. };
  5271. }
  5272. function expandToProperty(callback, targetKey) {
  5273. if (targetKey === void 0) { targetKey = null; }
  5274. return generateExpandMember(callback, targetKey);
  5275. }
  5276. BABYLON.expandToProperty = expandToProperty;
  5277. function serialize(sourceName) {
  5278. return generateSerializableMember(0, sourceName); // value member
  5279. }
  5280. BABYLON.serialize = serialize;
  5281. function serializeAsTexture(sourceName) {
  5282. return generateSerializableMember(1, sourceName); // texture member
  5283. }
  5284. BABYLON.serializeAsTexture = serializeAsTexture;
  5285. function serializeAsColor3(sourceName) {
  5286. return generateSerializableMember(2, sourceName); // color3 member
  5287. }
  5288. BABYLON.serializeAsColor3 = serializeAsColor3;
  5289. function serializeAsFresnelParameters(sourceName) {
  5290. return generateSerializableMember(3, sourceName); // fresnel parameters member
  5291. }
  5292. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  5293. function serializeAsVector2(sourceName) {
  5294. return generateSerializableMember(4, sourceName); // vector2 member
  5295. }
  5296. BABYLON.serializeAsVector2 = serializeAsVector2;
  5297. function serializeAsVector3(sourceName) {
  5298. return generateSerializableMember(5, sourceName); // vector3 member
  5299. }
  5300. BABYLON.serializeAsVector3 = serializeAsVector3;
  5301. function serializeAsMeshReference(sourceName) {
  5302. return generateSerializableMember(6, sourceName); // mesh reference member
  5303. }
  5304. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  5305. function serializeAsColorCurves(sourceName) {
  5306. return generateSerializableMember(7, sourceName); // color curves
  5307. }
  5308. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  5309. function serializeAsColor4(sourceName) {
  5310. return generateSerializableMember(8, sourceName); // color 4
  5311. }
  5312. BABYLON.serializeAsColor4 = serializeAsColor4;
  5313. function serializeAsImageProcessingConfiguration(sourceName) {
  5314. return generateSerializableMember(9, sourceName); // image processing
  5315. }
  5316. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  5317. function serializeAsQuaternion(sourceName) {
  5318. return generateSerializableMember(10, sourceName); // quaternion member
  5319. }
  5320. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  5321. var SerializationHelper = /** @class */ (function () {
  5322. function SerializationHelper() {
  5323. }
  5324. SerializationHelper.Serialize = function (entity, serializationObject) {
  5325. if (!serializationObject) {
  5326. serializationObject = {};
  5327. }
  5328. // Tags
  5329. if (BABYLON.Tags) {
  5330. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  5331. }
  5332. var serializedProperties = getMergedStore(entity);
  5333. // Properties
  5334. for (var property in serializedProperties) {
  5335. var propertyDescriptor = serializedProperties[property];
  5336. var targetPropertyName = propertyDescriptor.sourceName || property;
  5337. var propertyType = propertyDescriptor.type;
  5338. var sourceProperty = entity[property];
  5339. if (sourceProperty !== undefined && sourceProperty !== null) {
  5340. switch (propertyType) {
  5341. case 0:// Value
  5342. serializationObject[targetPropertyName] = sourceProperty;
  5343. break;
  5344. case 1:// Texture
  5345. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5346. break;
  5347. case 2:// Color3
  5348. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5349. break;
  5350. case 3:// FresnelParameters
  5351. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5352. break;
  5353. case 4:// Vector2
  5354. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5355. break;
  5356. case 5:// Vector3
  5357. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5358. break;
  5359. case 6:// Mesh reference
  5360. serializationObject[targetPropertyName] = sourceProperty.id;
  5361. break;
  5362. case 7:// Color Curves
  5363. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5364. break;
  5365. case 8:// Color 4
  5366. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5367. break;
  5368. case 9:// Image Processing
  5369. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5370. break;
  5371. }
  5372. }
  5373. }
  5374. return serializationObject;
  5375. };
  5376. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  5377. if (rootUrl === void 0) { rootUrl = null; }
  5378. var destination = creationFunction();
  5379. if (!rootUrl) {
  5380. rootUrl = "";
  5381. }
  5382. // Tags
  5383. if (BABYLON.Tags) {
  5384. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5385. }
  5386. var classStore = getMergedStore(destination);
  5387. // Properties
  5388. for (var property in classStore) {
  5389. var propertyDescriptor = classStore[property];
  5390. var sourceProperty = source[propertyDescriptor.sourceName || property];
  5391. var propertyType = propertyDescriptor.type;
  5392. if (sourceProperty !== undefined && sourceProperty !== null) {
  5393. var dest = destination;
  5394. switch (propertyType) {
  5395. case 0:// Value
  5396. dest[property] = sourceProperty;
  5397. break;
  5398. case 1:// Texture
  5399. if (scene) {
  5400. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  5401. }
  5402. break;
  5403. case 2:// Color3
  5404. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  5405. break;
  5406. case 3:// FresnelParameters
  5407. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  5408. break;
  5409. case 4:// Vector2
  5410. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  5411. break;
  5412. case 5:// Vector3
  5413. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  5414. break;
  5415. case 6:// Mesh reference
  5416. if (scene) {
  5417. dest[property] = scene.getLastMeshByID(sourceProperty);
  5418. }
  5419. break;
  5420. case 7:// Color Curves
  5421. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  5422. break;
  5423. case 8:// Color 4
  5424. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  5425. break;
  5426. case 9:// Image Processing
  5427. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  5428. break;
  5429. }
  5430. }
  5431. }
  5432. return destination;
  5433. };
  5434. SerializationHelper.Clone = function (creationFunction, source) {
  5435. return _copySource(creationFunction, source, false);
  5436. };
  5437. SerializationHelper.Instanciate = function (creationFunction, source) {
  5438. return _copySource(creationFunction, source, true);
  5439. };
  5440. return SerializationHelper;
  5441. }());
  5442. BABYLON.SerializationHelper = SerializationHelper;
  5443. })(BABYLON || (BABYLON = {}));
  5444. //# sourceMappingURL=babylon.decorators.js.map
  5445. var BABYLON;
  5446. (function (BABYLON) {
  5447. /**
  5448. * A class serves as a medium between the observable and its observers
  5449. */
  5450. var EventState = /** @class */ (function () {
  5451. /**
  5452. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  5453. */
  5454. function EventState(mask, skipNextObservers, target, currentTarget) {
  5455. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5456. this.initalize(mask, skipNextObservers, target, currentTarget);
  5457. }
  5458. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  5459. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5460. this.mask = mask;
  5461. this.skipNextObservers = skipNextObservers;
  5462. this.target = target;
  5463. this.currentTarget = currentTarget;
  5464. return this;
  5465. };
  5466. return EventState;
  5467. }());
  5468. BABYLON.EventState = EventState;
  5469. /**
  5470. * Represent an Observer registered to a given Observable object.
  5471. */
  5472. var Observer = /** @class */ (function () {
  5473. function Observer(callback, mask, scope) {
  5474. if (scope === void 0) { scope = null; }
  5475. this.callback = callback;
  5476. this.mask = mask;
  5477. this.scope = scope;
  5478. }
  5479. return Observer;
  5480. }());
  5481. BABYLON.Observer = Observer;
  5482. /**
  5483. * Represent a list of observers registered to multiple Observables object.
  5484. */
  5485. var MultiObserver = /** @class */ (function () {
  5486. function MultiObserver() {
  5487. }
  5488. MultiObserver.prototype.dispose = function () {
  5489. if (this._observers && this._observables) {
  5490. for (var index = 0; index < this._observers.length; index++) {
  5491. this._observables[index].remove(this._observers[index]);
  5492. }
  5493. }
  5494. this._observers = null;
  5495. this._observables = null;
  5496. };
  5497. MultiObserver.Watch = function (observables, callback, mask, scope) {
  5498. if (mask === void 0) { mask = -1; }
  5499. if (scope === void 0) { scope = null; }
  5500. var result = new MultiObserver();
  5501. result._observers = new Array();
  5502. result._observables = observables;
  5503. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  5504. var observable = observables_1[_i];
  5505. var observer = observable.add(callback, mask, false, scope);
  5506. if (observer) {
  5507. result._observers.push(observer);
  5508. }
  5509. }
  5510. return result;
  5511. };
  5512. return MultiObserver;
  5513. }());
  5514. BABYLON.MultiObserver = MultiObserver;
  5515. /**
  5516. * The Observable class is a simple implementation of the Observable pattern.
  5517. * 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.
  5518. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  5519. * 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).
  5520. * 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.
  5521. */
  5522. var Observable = /** @class */ (function () {
  5523. function Observable(onObserverAdded) {
  5524. this._observers = new Array();
  5525. this._eventState = new EventState(0);
  5526. if (onObserverAdded) {
  5527. this._onObserverAdded = onObserverAdded;
  5528. }
  5529. }
  5530. /**
  5531. * Create a new Observer with the specified callback
  5532. * @param callback the callback that will be executed for that Observer
  5533. * @param mask the mask used to filter observers
  5534. * @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.
  5535. * @param scope optional scope for the callback to be called from
  5536. */
  5537. Observable.prototype.add = function (callback, mask, insertFirst, scope) {
  5538. if (mask === void 0) { mask = -1; }
  5539. if (insertFirst === void 0) { insertFirst = false; }
  5540. if (scope === void 0) { scope = null; }
  5541. if (!callback) {
  5542. return null;
  5543. }
  5544. var observer = new Observer(callback, mask, scope);
  5545. if (insertFirst) {
  5546. this._observers.unshift(observer);
  5547. }
  5548. else {
  5549. this._observers.push(observer);
  5550. }
  5551. if (this._onObserverAdded) {
  5552. this._onObserverAdded(observer);
  5553. }
  5554. return observer;
  5555. };
  5556. /**
  5557. * Remove an Observer from the Observable object
  5558. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  5559. */
  5560. Observable.prototype.remove = function (observer) {
  5561. if (!observer) {
  5562. return false;
  5563. }
  5564. var index = this._observers.indexOf(observer);
  5565. if (index !== -1) {
  5566. this._observers.splice(index, 1);
  5567. return true;
  5568. }
  5569. return false;
  5570. };
  5571. /**
  5572. * Remove a callback from the Observable object
  5573. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5574. */
  5575. Observable.prototype.removeCallback = function (callback) {
  5576. for (var index = 0; index < this._observers.length; index++) {
  5577. if (this._observers[index].callback === callback) {
  5578. this._observers.splice(index, 1);
  5579. return true;
  5580. }
  5581. }
  5582. return false;
  5583. };
  5584. /**
  5585. * Notify all Observers by calling their respective callback with the given data
  5586. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5587. * @param eventData
  5588. * @param mask
  5589. */
  5590. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  5591. if (mask === void 0) { mask = -1; }
  5592. if (!this._observers.length) {
  5593. return true;
  5594. }
  5595. var state = this._eventState;
  5596. state.mask = mask;
  5597. state.target = target;
  5598. state.currentTarget = currentTarget;
  5599. state.skipNextObservers = false;
  5600. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5601. var obs = _a[_i];
  5602. if (obs.mask & mask) {
  5603. if (obs.scope) {
  5604. obs.callback.apply(obs.scope, [eventData, state]);
  5605. }
  5606. else {
  5607. obs.callback(eventData, state);
  5608. }
  5609. }
  5610. if (state.skipNextObservers) {
  5611. return false;
  5612. }
  5613. }
  5614. return true;
  5615. };
  5616. /**
  5617. * Notify a specific observer
  5618. * @param eventData
  5619. * @param mask
  5620. */
  5621. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  5622. if (mask === void 0) { mask = -1; }
  5623. var state = this._eventState;
  5624. state.mask = mask;
  5625. state.skipNextObservers = false;
  5626. observer.callback(eventData, state);
  5627. };
  5628. /**
  5629. * return true is the Observable has at least one Observer registered
  5630. */
  5631. Observable.prototype.hasObservers = function () {
  5632. return this._observers.length > 0;
  5633. };
  5634. /**
  5635. * Clear the list of observers
  5636. */
  5637. Observable.prototype.clear = function () {
  5638. this._observers = new Array();
  5639. this._onObserverAdded = null;
  5640. };
  5641. /**
  5642. * Clone the current observable
  5643. */
  5644. Observable.prototype.clone = function () {
  5645. var result = new Observable();
  5646. result._observers = this._observers.slice(0);
  5647. return result;
  5648. };
  5649. /**
  5650. * Does this observable handles observer registered with a given mask
  5651. * @param {number} trigger - the mask to be tested
  5652. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5653. **/
  5654. Observable.prototype.hasSpecificMask = function (mask) {
  5655. if (mask === void 0) { mask = -1; }
  5656. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5657. var obs = _a[_i];
  5658. if (obs.mask & mask || obs.mask === mask) {
  5659. return true;
  5660. }
  5661. }
  5662. return false;
  5663. };
  5664. return Observable;
  5665. }());
  5666. BABYLON.Observable = Observable;
  5667. })(BABYLON || (BABYLON = {}));
  5668. //# sourceMappingURL=babylon.observable.js.map
  5669. var BABYLON;
  5670. (function (BABYLON) {
  5671. var SmartArray = /** @class */ (function () {
  5672. function SmartArray(capacity) {
  5673. this.length = 0;
  5674. this.data = new Array(capacity);
  5675. this._id = SmartArray._GlobalId++;
  5676. }
  5677. SmartArray.prototype.push = function (value) {
  5678. this.data[this.length++] = value;
  5679. if (this.length > this.data.length) {
  5680. this.data.length *= 2;
  5681. }
  5682. };
  5683. SmartArray.prototype.forEach = function (func) {
  5684. for (var index = 0; index < this.length; index++) {
  5685. func(this.data[index]);
  5686. }
  5687. };
  5688. SmartArray.prototype.sort = function (compareFn) {
  5689. this.data.sort(compareFn);
  5690. };
  5691. SmartArray.prototype.reset = function () {
  5692. this.length = 0;
  5693. };
  5694. SmartArray.prototype.dispose = function () {
  5695. this.reset();
  5696. if (this.data) {
  5697. this.data.length = 0;
  5698. this.data = [];
  5699. }
  5700. };
  5701. SmartArray.prototype.concat = function (array) {
  5702. if (array.length === 0) {
  5703. return;
  5704. }
  5705. if (this.length + array.length > this.data.length) {
  5706. this.data.length = (this.length + array.length) * 2;
  5707. }
  5708. for (var index = 0; index < array.length; index++) {
  5709. this.data[this.length++] = (array.data || array)[index];
  5710. }
  5711. };
  5712. SmartArray.prototype.indexOf = function (value) {
  5713. var position = this.data.indexOf(value);
  5714. if (position >= this.length) {
  5715. return -1;
  5716. }
  5717. return position;
  5718. };
  5719. SmartArray.prototype.contains = function (value) {
  5720. return this.data.indexOf(value) !== -1;
  5721. };
  5722. // Statics
  5723. SmartArray._GlobalId = 0;
  5724. return SmartArray;
  5725. }());
  5726. BABYLON.SmartArray = SmartArray;
  5727. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  5728. __extends(SmartArrayNoDuplicate, _super);
  5729. function SmartArrayNoDuplicate() {
  5730. var _this = _super !== null && _super.apply(this, arguments) || this;
  5731. _this._duplicateId = 0;
  5732. return _this;
  5733. }
  5734. SmartArrayNoDuplicate.prototype.push = function (value) {
  5735. _super.prototype.push.call(this, value);
  5736. if (!value.__smartArrayFlags) {
  5737. value.__smartArrayFlags = {};
  5738. }
  5739. value.__smartArrayFlags[this._id] = this._duplicateId;
  5740. };
  5741. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  5742. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5743. return false;
  5744. }
  5745. this.push(value);
  5746. return true;
  5747. };
  5748. SmartArrayNoDuplicate.prototype.reset = function () {
  5749. _super.prototype.reset.call(this);
  5750. this._duplicateId++;
  5751. };
  5752. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  5753. if (array.length === 0) {
  5754. return;
  5755. }
  5756. if (this.length + array.length > this.data.length) {
  5757. this.data.length = (this.length + array.length) * 2;
  5758. }
  5759. for (var index = 0; index < array.length; index++) {
  5760. var item = (array.data || array)[index];
  5761. this.pushNoDuplicate(item);
  5762. }
  5763. };
  5764. return SmartArrayNoDuplicate;
  5765. }(SmartArray));
  5766. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  5767. })(BABYLON || (BABYLON = {}));
  5768. //# sourceMappingURL=babylon.smartArray.js.map
  5769. var BABYLON;
  5770. (function (BABYLON) {
  5771. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  5772. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  5773. var LoadFileError = /** @class */ (function (_super) {
  5774. __extends(LoadFileError, _super);
  5775. function LoadFileError(message, request) {
  5776. var _this = _super.call(this, message) || this;
  5777. _this.request = request;
  5778. _this.name = "LoadFileError";
  5779. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  5780. return _this;
  5781. }
  5782. // Polyfill for Object.setPrototypeOf if necessary.
  5783. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  5784. return LoadFileError;
  5785. }(Error));
  5786. BABYLON.LoadFileError = LoadFileError;
  5787. var RetryStrategy = /** @class */ (function () {
  5788. function RetryStrategy() {
  5789. }
  5790. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  5791. if (maxRetries === void 0) { maxRetries = 3; }
  5792. if (baseInterval === void 0) { baseInterval = 500; }
  5793. return function (url, request, retryIndex) {
  5794. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  5795. return -1;
  5796. }
  5797. return Math.pow(2, retryIndex) * baseInterval;
  5798. };
  5799. };
  5800. return RetryStrategy;
  5801. }());
  5802. BABYLON.RetryStrategy = RetryStrategy;
  5803. // Screenshots
  5804. var screenshotCanvas;
  5805. var cloneValue = function (source, destinationObject) {
  5806. if (!source)
  5807. return null;
  5808. if (source instanceof BABYLON.Mesh) {
  5809. return null;
  5810. }
  5811. if (source instanceof BABYLON.SubMesh) {
  5812. return source.clone(destinationObject);
  5813. }
  5814. else if (source.clone) {
  5815. return source.clone();
  5816. }
  5817. return null;
  5818. };
  5819. var Tools = /** @class */ (function () {
  5820. function Tools() {
  5821. }
  5822. /**
  5823. * Interpolates between a and b via alpha
  5824. * @param a The lower value (returned when alpha = 0)
  5825. * @param b The upper value (returned when alpha = 1)
  5826. * @param alpha The interpolation-factor
  5827. * @return The mixed value
  5828. */
  5829. Tools.Mix = function (a, b, alpha) {
  5830. return a * (1 - alpha) + b * alpha;
  5831. };
  5832. Tools.Instantiate = function (className) {
  5833. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  5834. return Tools.RegisteredExternalClasses[className];
  5835. }
  5836. var arr = className.split(".");
  5837. var fn = (window || this);
  5838. for (var i = 0, len = arr.length; i < len; i++) {
  5839. fn = fn[arr[i]];
  5840. }
  5841. if (typeof fn !== "function") {
  5842. return null;
  5843. }
  5844. return fn;
  5845. };
  5846. Tools.SetImmediate = function (action) {
  5847. if (window.setImmediate) {
  5848. window.setImmediate(action);
  5849. }
  5850. else {
  5851. setTimeout(action, 1);
  5852. }
  5853. };
  5854. Tools.IsExponentOfTwo = function (value) {
  5855. var count = 1;
  5856. do {
  5857. count *= 2;
  5858. } while (count < value);
  5859. return count === value;
  5860. };
  5861. /**
  5862. * Find the next highest power of two.
  5863. * @param x Number to start search from.
  5864. * @return Next highest power of two.
  5865. */
  5866. Tools.CeilingPOT = function (x) {
  5867. x--;
  5868. x |= x >> 1;
  5869. x |= x >> 2;
  5870. x |= x >> 4;
  5871. x |= x >> 8;
  5872. x |= x >> 16;
  5873. x++;
  5874. return x;
  5875. };
  5876. /**
  5877. * Find the next lowest power of two.
  5878. * @param x Number to start search from.
  5879. * @return Next lowest power of two.
  5880. */
  5881. Tools.FloorPOT = function (x) {
  5882. x = x | (x >> 1);
  5883. x = x | (x >> 2);
  5884. x = x | (x >> 4);
  5885. x = x | (x >> 8);
  5886. x = x | (x >> 16);
  5887. return x - (x >> 1);
  5888. };
  5889. /**
  5890. * Find the nearest power of two.
  5891. * @param x Number to start search from.
  5892. * @return Next nearest power of two.
  5893. */
  5894. Tools.NearestPOT = function (x) {
  5895. var c = Tools.CeilingPOT(x);
  5896. var f = Tools.FloorPOT(x);
  5897. return (c - x) > (x - f) ? f : c;
  5898. };
  5899. Tools.GetExponentOfTwo = function (value, max, mode) {
  5900. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5901. var pot;
  5902. switch (mode) {
  5903. case BABYLON.Engine.SCALEMODE_FLOOR:
  5904. pot = Tools.FloorPOT(value);
  5905. break;
  5906. case BABYLON.Engine.SCALEMODE_NEAREST:
  5907. pot = Tools.NearestPOT(value);
  5908. break;
  5909. case BABYLON.Engine.SCALEMODE_CEILING:
  5910. default:
  5911. pot = Tools.CeilingPOT(value);
  5912. break;
  5913. }
  5914. return Math.min(pot, max);
  5915. };
  5916. Tools.GetFilename = function (path) {
  5917. var index = path.lastIndexOf("/");
  5918. if (index < 0)
  5919. return path;
  5920. return path.substring(index + 1);
  5921. };
  5922. Tools.GetFolderPath = function (uri) {
  5923. var index = uri.lastIndexOf("/");
  5924. if (index < 0)
  5925. return "";
  5926. return uri.substring(0, index + 1);
  5927. };
  5928. Tools.GetDOMTextContent = function (element) {
  5929. var result = "";
  5930. var child = element.firstChild;
  5931. while (child) {
  5932. if (child.nodeType === 3) {
  5933. result += child.textContent;
  5934. }
  5935. child = child.nextSibling;
  5936. }
  5937. return result;
  5938. };
  5939. Tools.ToDegrees = function (angle) {
  5940. return angle * 180 / Math.PI;
  5941. };
  5942. Tools.ToRadians = function (angle) {
  5943. return angle * Math.PI / 180;
  5944. };
  5945. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5946. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5947. var output = "";
  5948. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5949. var i = 0;
  5950. var bytes = new Uint8Array(buffer);
  5951. while (i < bytes.length) {
  5952. chr1 = bytes[i++];
  5953. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5954. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5955. enc1 = chr1 >> 2;
  5956. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5957. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5958. enc4 = chr3 & 63;
  5959. if (isNaN(chr2)) {
  5960. enc3 = enc4 = 64;
  5961. }
  5962. else if (isNaN(chr3)) {
  5963. enc4 = 64;
  5964. }
  5965. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5966. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5967. }
  5968. return "data:image/png;base64," + output;
  5969. };
  5970. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5971. if (bias === void 0) { bias = null; }
  5972. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5973. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5974. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5975. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5976. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5977. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5978. }
  5979. if (bias) {
  5980. minimum.x -= minimum.x * bias.x + bias.y;
  5981. minimum.y -= minimum.y * bias.x + bias.y;
  5982. minimum.z -= minimum.z * bias.x + bias.y;
  5983. maximum.x += maximum.x * bias.x + bias.y;
  5984. maximum.y += maximum.y * bias.x + bias.y;
  5985. maximum.z += maximum.z * bias.x + bias.y;
  5986. }
  5987. return {
  5988. minimum: minimum,
  5989. maximum: maximum
  5990. };
  5991. };
  5992. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5993. if (bias === void 0) { bias = null; }
  5994. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5995. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5996. if (!stride) {
  5997. stride = 3;
  5998. }
  5999. for (var index = start; index < start + count; index++) {
  6000. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  6001. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6002. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6003. }
  6004. if (bias) {
  6005. minimum.x -= minimum.x * bias.x + bias.y;
  6006. minimum.y -= minimum.y * bias.x + bias.y;
  6007. minimum.z -= minimum.z * bias.x + bias.y;
  6008. maximum.x += maximum.x * bias.x + bias.y;
  6009. maximum.y += maximum.y * bias.x + bias.y;
  6010. maximum.z += maximum.z * bias.x + bias.y;
  6011. }
  6012. return {
  6013. minimum: minimum,
  6014. maximum: maximum
  6015. };
  6016. };
  6017. Tools.Vector2ArrayFeeder = function (array) {
  6018. return function (index) {
  6019. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  6020. var length = isFloatArray ? array.length / 2 : array.length;
  6021. if (index >= length) {
  6022. return null;
  6023. }
  6024. if (isFloatArray) {
  6025. var fa = array;
  6026. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  6027. }
  6028. var a = array;
  6029. return a[index];
  6030. };
  6031. };
  6032. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  6033. if (bias === void 0) { bias = null; }
  6034. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  6035. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  6036. var i = 0;
  6037. var cur = feeder(i++);
  6038. while (cur) {
  6039. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  6040. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  6041. cur = feeder(i++);
  6042. }
  6043. if (bias) {
  6044. minimum.x -= minimum.x * bias.x + bias.y;
  6045. minimum.y -= minimum.y * bias.x + bias.y;
  6046. maximum.x += maximum.x * bias.x + bias.y;
  6047. maximum.y += maximum.y * bias.x + bias.y;
  6048. }
  6049. return {
  6050. minimum: minimum,
  6051. maximum: maximum
  6052. };
  6053. };
  6054. Tools.MakeArray = function (obj, allowsNullUndefined) {
  6055. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  6056. return null;
  6057. return Array.isArray(obj) ? obj : [obj];
  6058. };
  6059. // Misc.
  6060. Tools.GetPointerPrefix = function () {
  6061. var eventPrefix = "pointer";
  6062. // Check if pointer events are supported
  6063. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  6064. eventPrefix = "mouse";
  6065. }
  6066. return eventPrefix;
  6067. };
  6068. /**
  6069. * @param func - the function to be called
  6070. * @param requester - the object that will request the next frame. Falls back to window.
  6071. */
  6072. Tools.QueueNewFrame = function (func, requester) {
  6073. if (!Tools.IsWindowObjectExist()) {
  6074. return setTimeout(func, 16);
  6075. }
  6076. if (!requester) {
  6077. requester = window;
  6078. }
  6079. if (requester.requestAnimationFrame) {
  6080. return requester.requestAnimationFrame(func);
  6081. }
  6082. else if (requester.msRequestAnimationFrame) {
  6083. return requester.msRequestAnimationFrame(func);
  6084. }
  6085. else if (requester.webkitRequestAnimationFrame) {
  6086. return requester.webkitRequestAnimationFrame(func);
  6087. }
  6088. else if (requester.mozRequestAnimationFrame) {
  6089. return requester.mozRequestAnimationFrame(func);
  6090. }
  6091. else if (requester.oRequestAnimationFrame) {
  6092. return requester.oRequestAnimationFrame(func);
  6093. }
  6094. else {
  6095. return window.setTimeout(func, 16);
  6096. }
  6097. };
  6098. Tools.RequestFullscreen = function (element) {
  6099. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  6100. if (!requestFunction)
  6101. return;
  6102. requestFunction.call(element);
  6103. };
  6104. Tools.ExitFullscreen = function () {
  6105. if (document.exitFullscreen) {
  6106. document.exitFullscreen();
  6107. }
  6108. else if (document.mozCancelFullScreen) {
  6109. document.mozCancelFullScreen();
  6110. }
  6111. else if (document.webkitCancelFullScreen) {
  6112. document.webkitCancelFullScreen();
  6113. }
  6114. else if (document.msCancelFullScreen) {
  6115. document.msCancelFullScreen();
  6116. }
  6117. };
  6118. Tools.SetCorsBehavior = function (url, element) {
  6119. if (url && url.indexOf("data:") === 0) {
  6120. return;
  6121. }
  6122. if (Tools.CorsBehavior) {
  6123. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  6124. element.crossOrigin = Tools.CorsBehavior;
  6125. }
  6126. else {
  6127. var result = Tools.CorsBehavior(url);
  6128. if (result) {
  6129. element.crossOrigin = result;
  6130. }
  6131. }
  6132. }
  6133. };
  6134. // External files
  6135. Tools.CleanUrl = function (url) {
  6136. url = url.replace(/#/mg, "%23");
  6137. return url;
  6138. };
  6139. Tools.LoadImage = function (url, onLoad, onError, database) {
  6140. if (url instanceof ArrayBuffer) {
  6141. url = Tools.EncodeArrayBufferTobase64(url);
  6142. }
  6143. url = Tools.CleanUrl(url);
  6144. url = Tools.PreprocessUrl(url);
  6145. var img = new Image();
  6146. Tools.SetCorsBehavior(url, img);
  6147. img.onload = function () {
  6148. onLoad(img);
  6149. };
  6150. img.onerror = function (err) {
  6151. Tools.Error("Error while trying to load image: " + url);
  6152. if (onError) {
  6153. onError("Error while trying to load image: " + url, err);
  6154. }
  6155. };
  6156. var noIndexedDB = function () {
  6157. img.src = url;
  6158. };
  6159. var loadFromIndexedDB = function () {
  6160. if (database) {
  6161. database.loadImageFromDB(url, img);
  6162. }
  6163. };
  6164. //ANY database to do!
  6165. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  6166. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6167. }
  6168. else {
  6169. if (url.indexOf("file:") !== -1) {
  6170. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  6171. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  6172. try {
  6173. var blobURL;
  6174. try {
  6175. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  6176. }
  6177. catch (ex) {
  6178. // Chrome doesn't support oneTimeOnly parameter
  6179. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  6180. }
  6181. img.src = blobURL;
  6182. }
  6183. catch (e) {
  6184. img.src = "";
  6185. }
  6186. return img;
  6187. }
  6188. }
  6189. noIndexedDB();
  6190. }
  6191. return img;
  6192. };
  6193. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  6194. url = Tools.CleanUrl(url);
  6195. url = Tools.PreprocessUrl(url);
  6196. // If file and file input are set
  6197. if (url.indexOf("file:") !== -1) {
  6198. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  6199. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  6200. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  6201. }
  6202. }
  6203. var loadUrl = Tools.BaseUrl + url;
  6204. var aborted = false;
  6205. var fileRequest = {
  6206. onCompleteObservable: new BABYLON.Observable(),
  6207. abort: function () { return aborted = true; },
  6208. };
  6209. var requestFile = function () {
  6210. var request = new XMLHttpRequest();
  6211. var retryHandle = null;
  6212. fileRequest.abort = function () {
  6213. aborted = true;
  6214. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  6215. request.abort();
  6216. }
  6217. if (retryHandle !== null) {
  6218. clearTimeout(retryHandle);
  6219. retryHandle = null;
  6220. }
  6221. };
  6222. var retryLoop = function (retryIndex) {
  6223. request.open('GET', loadUrl, true);
  6224. if (useArrayBuffer) {
  6225. request.responseType = "arraybuffer";
  6226. }
  6227. if (onProgress) {
  6228. request.addEventListener("progress", onProgress);
  6229. }
  6230. var onLoadEnd = function () {
  6231. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  6232. };
  6233. request.addEventListener("loadend", onLoadEnd);
  6234. var onReadyStateChange = function () {
  6235. if (aborted) {
  6236. return;
  6237. }
  6238. // In case of undefined state in some browsers.
  6239. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  6240. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  6241. request.removeEventListener("readystatechange", onReadyStateChange);
  6242. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  6243. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  6244. return;
  6245. }
  6246. var retryStrategy = Tools.DefaultRetryStrategy;
  6247. if (retryStrategy) {
  6248. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  6249. if (waitTime !== -1) {
  6250. // Prevent the request from completing for retry.
  6251. request.removeEventListener("loadend", onLoadEnd);
  6252. request = new XMLHttpRequest();
  6253. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  6254. return;
  6255. }
  6256. }
  6257. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  6258. if (onError) {
  6259. onError(request, e);
  6260. }
  6261. else {
  6262. throw e;
  6263. }
  6264. }
  6265. };
  6266. request.addEventListener("readystatechange", onReadyStateChange);
  6267. request.send();
  6268. };
  6269. retryLoop(0);
  6270. };
  6271. // Caching all files
  6272. if (database && database.enableSceneOffline) {
  6273. var noIndexedDB_1 = function () {
  6274. if (!aborted) {
  6275. requestFile();
  6276. }
  6277. };
  6278. var loadFromIndexedDB = function () {
  6279. // TODO: database needs to support aborting and should return a IFileRequest
  6280. if (aborted) {
  6281. return;
  6282. }
  6283. if (database) {
  6284. database.loadFileFromDB(url, function (data) {
  6285. if (!aborted) {
  6286. onSuccess(data);
  6287. }
  6288. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  6289. }, onProgress ? function (event) {
  6290. if (!aborted) {
  6291. onProgress(event);
  6292. }
  6293. } : undefined, noIndexedDB_1, useArrayBuffer);
  6294. }
  6295. };
  6296. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  6297. }
  6298. else {
  6299. requestFile();
  6300. }
  6301. return fileRequest;
  6302. };
  6303. /**
  6304. * Load a script (identified by an url). When the url returns, the
  6305. * content of this file is added into a new script element, attached to the DOM (body element)
  6306. */
  6307. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  6308. var head = document.getElementsByTagName('head')[0];
  6309. var script = document.createElement('script');
  6310. script.type = 'text/javascript';
  6311. script.src = scriptUrl;
  6312. script.onload = function () {
  6313. if (onSuccess) {
  6314. onSuccess();
  6315. }
  6316. };
  6317. script.onerror = function (e) {
  6318. if (onError) {
  6319. onError("Unable to load script", e);
  6320. }
  6321. };
  6322. head.appendChild(script);
  6323. };
  6324. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  6325. var reader = new FileReader();
  6326. var request = {
  6327. onCompleteObservable: new BABYLON.Observable(),
  6328. abort: function () { return reader.abort(); },
  6329. };
  6330. reader.onloadend = function (e) {
  6331. request.onCompleteObservable.notifyObservers(request);
  6332. };
  6333. reader.onload = function (e) {
  6334. //target doesn't have result from ts 1.3
  6335. callback(e.target['result']);
  6336. };
  6337. reader.onprogress = progressCallback;
  6338. reader.readAsDataURL(fileToLoad);
  6339. return request;
  6340. };
  6341. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  6342. var reader = new FileReader();
  6343. var request = {
  6344. onCompleteObservable: new BABYLON.Observable(),
  6345. abort: function () { return reader.abort(); },
  6346. };
  6347. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  6348. reader.onerror = function (e) {
  6349. Tools.Log("Error while reading file: " + fileToLoad.name);
  6350. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  6351. };
  6352. reader.onload = function (e) {
  6353. //target doesn't have result from ts 1.3
  6354. callback(e.target['result']);
  6355. };
  6356. if (progressCallBack) {
  6357. reader.onprogress = progressCallBack;
  6358. }
  6359. if (!useArrayBuffer) {
  6360. // Asynchronous read
  6361. reader.readAsText(fileToLoad);
  6362. }
  6363. else {
  6364. reader.readAsArrayBuffer(fileToLoad);
  6365. }
  6366. return request;
  6367. };
  6368. //returns a downloadable url to a file content.
  6369. Tools.FileAsURL = function (content) {
  6370. var fileBlob = new Blob([content]);
  6371. var url = window.URL || window.webkitURL;
  6372. var link = url.createObjectURL(fileBlob);
  6373. return link;
  6374. };
  6375. // Misc.
  6376. Tools.Format = function (value, decimals) {
  6377. if (decimals === void 0) { decimals = 2; }
  6378. return value.toFixed(decimals);
  6379. };
  6380. Tools.CheckExtends = function (v, min, max) {
  6381. if (v.x < min.x)
  6382. min.x = v.x;
  6383. if (v.y < min.y)
  6384. min.y = v.y;
  6385. if (v.z < min.z)
  6386. min.z = v.z;
  6387. if (v.x > max.x)
  6388. max.x = v.x;
  6389. if (v.y > max.y)
  6390. max.y = v.y;
  6391. if (v.z > max.z)
  6392. max.z = v.z;
  6393. };
  6394. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  6395. for (var prop in source) {
  6396. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  6397. continue;
  6398. }
  6399. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  6400. continue;
  6401. }
  6402. var sourceValue = source[prop];
  6403. var typeOfSourceValue = typeof sourceValue;
  6404. if (typeOfSourceValue === "function") {
  6405. continue;
  6406. }
  6407. if (typeOfSourceValue === "object") {
  6408. if (sourceValue instanceof Array) {
  6409. destination[prop] = [];
  6410. if (sourceValue.length > 0) {
  6411. if (typeof sourceValue[0] == "object") {
  6412. for (var index = 0; index < sourceValue.length; index++) {
  6413. var clonedValue = cloneValue(sourceValue[index], destination);
  6414. if (destination[prop].indexOf(clonedValue) === -1) {
  6415. destination[prop].push(clonedValue);
  6416. }
  6417. }
  6418. }
  6419. else {
  6420. destination[prop] = sourceValue.slice(0);
  6421. }
  6422. }
  6423. }
  6424. else {
  6425. destination[prop] = cloneValue(sourceValue, destination);
  6426. }
  6427. }
  6428. else {
  6429. destination[prop] = sourceValue;
  6430. }
  6431. }
  6432. };
  6433. Tools.IsEmpty = function (obj) {
  6434. for (var i in obj) {
  6435. if (obj.hasOwnProperty(i)) {
  6436. return false;
  6437. }
  6438. }
  6439. return true;
  6440. };
  6441. Tools.RegisterTopRootEvents = function (events) {
  6442. for (var index = 0; index < events.length; index++) {
  6443. var event = events[index];
  6444. window.addEventListener(event.name, event.handler, false);
  6445. try {
  6446. if (window.parent) {
  6447. window.parent.addEventListener(event.name, event.handler, false);
  6448. }
  6449. }
  6450. catch (e) {
  6451. // Silently fails...
  6452. }
  6453. }
  6454. };
  6455. Tools.UnregisterTopRootEvents = function (events) {
  6456. for (var index = 0; index < events.length; index++) {
  6457. var event = events[index];
  6458. window.removeEventListener(event.name, event.handler);
  6459. try {
  6460. if (window.parent) {
  6461. window.parent.removeEventListener(event.name, event.handler);
  6462. }
  6463. }
  6464. catch (e) {
  6465. // Silently fails...
  6466. }
  6467. }
  6468. };
  6469. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  6470. if (mimeType === void 0) { mimeType = "image/png"; }
  6471. // Read the contents of the framebuffer
  6472. var numberOfChannelsByLine = width * 4;
  6473. var halfHeight = height / 2;
  6474. //Reading datas from WebGL
  6475. var data = engine.readPixels(0, 0, width, height);
  6476. //To flip image on Y axis.
  6477. for (var i = 0; i < halfHeight; i++) {
  6478. for (var j = 0; j < numberOfChannelsByLine; j++) {
  6479. var currentCell = j + i * numberOfChannelsByLine;
  6480. var targetLine = height - i - 1;
  6481. var targetCell = j + targetLine * numberOfChannelsByLine;
  6482. var temp = data[currentCell];
  6483. data[currentCell] = data[targetCell];
  6484. data[targetCell] = temp;
  6485. }
  6486. }
  6487. // Create a 2D canvas to store the result
  6488. if (!screenshotCanvas) {
  6489. screenshotCanvas = document.createElement('canvas');
  6490. }
  6491. screenshotCanvas.width = width;
  6492. screenshotCanvas.height = height;
  6493. var context = screenshotCanvas.getContext('2d');
  6494. if (context) {
  6495. // Copy the pixels to a 2D canvas
  6496. var imageData = context.createImageData(width, height);
  6497. var castData = (imageData.data);
  6498. castData.set(data);
  6499. context.putImageData(imageData, 0, 0);
  6500. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  6501. }
  6502. };
  6503. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  6504. if (mimeType === void 0) { mimeType = "image/png"; }
  6505. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6506. if (successCallback) {
  6507. successCallback(base64Image);
  6508. }
  6509. else {
  6510. // We need HTMLCanvasElement.toBlob for HD screenshots
  6511. if (!screenshotCanvas.toBlob) {
  6512. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  6513. screenshotCanvas.toBlob = function (callback, type, quality) {
  6514. var _this = this;
  6515. setTimeout(function () {
  6516. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  6517. for (var i = 0; i < len; i++) {
  6518. arr[i] = binStr.charCodeAt(i);
  6519. }
  6520. callback(new Blob([arr], { type: type || 'image/png' }));
  6521. });
  6522. };
  6523. }
  6524. screenshotCanvas.toBlob(function (blob) {
  6525. var url = URL.createObjectURL(blob);
  6526. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6527. if (("download" in document.createElement("a"))) {
  6528. var a = window.document.createElement("a");
  6529. a.href = url;
  6530. if (fileName) {
  6531. a.setAttribute("download", fileName);
  6532. }
  6533. else {
  6534. var date = new Date();
  6535. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6536. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6537. }
  6538. window.document.body.appendChild(a);
  6539. a.addEventListener("click", function () {
  6540. if (a.parentElement) {
  6541. a.parentElement.removeChild(a);
  6542. }
  6543. });
  6544. a.click();
  6545. }
  6546. else {
  6547. var newWindow = window.open("");
  6548. if (!newWindow)
  6549. return;
  6550. var img = newWindow.document.createElement("img");
  6551. img.onload = function () {
  6552. // no longer need to read the blob so it's revoked
  6553. URL.revokeObjectURL(url);
  6554. };
  6555. img.src = url;
  6556. newWindow.document.body.appendChild(img);
  6557. }
  6558. });
  6559. }
  6560. };
  6561. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6562. if (mimeType === void 0) { mimeType = "image/png"; }
  6563. var width;
  6564. var height;
  6565. // If a precision value is specified
  6566. if (size.precision) {
  6567. width = Math.round(engine.getRenderWidth() * size.precision);
  6568. height = Math.round(width / engine.getAspectRatio(camera));
  6569. }
  6570. else if (size.width && size.height) {
  6571. width = size.width;
  6572. height = size.height;
  6573. }
  6574. else if (size.width && !size.height) {
  6575. width = size.width;
  6576. height = Math.round(width / engine.getAspectRatio(camera));
  6577. }
  6578. else if (size.height && !size.width) {
  6579. height = size.height;
  6580. width = Math.round(height * engine.getAspectRatio(camera));
  6581. }
  6582. else if (!isNaN(size)) {
  6583. height = size;
  6584. width = size;
  6585. }
  6586. else {
  6587. Tools.Error("Invalid 'size' parameter !");
  6588. return;
  6589. }
  6590. if (!screenshotCanvas) {
  6591. screenshotCanvas = document.createElement('canvas');
  6592. }
  6593. screenshotCanvas.width = width;
  6594. screenshotCanvas.height = height;
  6595. var renderContext = screenshotCanvas.getContext("2d");
  6596. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6597. var newWidth = width;
  6598. var newHeight = newWidth / ratio;
  6599. if (newHeight > height) {
  6600. newHeight = height;
  6601. newWidth = newHeight * ratio;
  6602. }
  6603. var offsetX = Math.max(0, width - newWidth) / 2;
  6604. var offsetY = Math.max(0, height - newHeight) / 2;
  6605. var renderingCanvas = engine.getRenderingCanvas();
  6606. if (renderContext && renderingCanvas) {
  6607. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  6608. }
  6609. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6610. };
  6611. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  6612. if (mimeType === void 0) { mimeType = "image/png"; }
  6613. if (samples === void 0) { samples = 1; }
  6614. if (antialiasing === void 0) { antialiasing = false; }
  6615. var width;
  6616. var height;
  6617. //If a precision value is specified
  6618. if (size.precision) {
  6619. width = Math.round(engine.getRenderWidth() * size.precision);
  6620. height = Math.round(width / engine.getAspectRatio(camera));
  6621. size = { width: width, height: height };
  6622. }
  6623. else if (size.width && size.height) {
  6624. width = size.width;
  6625. height = size.height;
  6626. }
  6627. else if (size.width && !size.height) {
  6628. width = size.width;
  6629. height = Math.round(width / engine.getAspectRatio(camera));
  6630. size = { width: width, height: height };
  6631. }
  6632. else if (size.height && !size.width) {
  6633. height = size.height;
  6634. width = Math.round(height * engine.getAspectRatio(camera));
  6635. size = { width: width, height: height };
  6636. }
  6637. else if (!isNaN(size)) {
  6638. height = size;
  6639. width = size;
  6640. }
  6641. else {
  6642. Tools.Error("Invalid 'size' parameter !");
  6643. return;
  6644. }
  6645. var scene = camera.getScene();
  6646. var previousCamera = null;
  6647. if (scene.activeCamera !== camera) {
  6648. previousCamera = scene.activeCamera;
  6649. scene.activeCamera = camera;
  6650. }
  6651. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6652. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6653. texture.renderList = null;
  6654. texture.samples = samples;
  6655. if (antialiasing) {
  6656. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  6657. }
  6658. texture.onAfterRenderObservable.add(function () {
  6659. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  6660. });
  6661. scene.incrementRenderId();
  6662. scene.resetCachedMaterial();
  6663. texture.render(true);
  6664. texture.dispose();
  6665. if (previousCamera) {
  6666. scene.activeCamera = previousCamera;
  6667. }
  6668. camera.getProjectionMatrix(true); // Force cache refresh;
  6669. };
  6670. // XHR response validator for local file scenario
  6671. Tools.ValidateXHRData = function (xhr, dataType) {
  6672. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6673. if (dataType === void 0) { dataType = 7; }
  6674. try {
  6675. if (dataType & 1) {
  6676. if (xhr.responseText && xhr.responseText.length > 0) {
  6677. return true;
  6678. }
  6679. else if (dataType === 1) {
  6680. return false;
  6681. }
  6682. }
  6683. if (dataType & 2) {
  6684. // Check header width and height since there is no "TGA" magic number
  6685. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6686. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6687. return true;
  6688. }
  6689. else if (dataType === 2) {
  6690. return false;
  6691. }
  6692. }
  6693. if (dataType & 4) {
  6694. // Check for the "DDS" magic number
  6695. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6696. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6697. return true;
  6698. }
  6699. else {
  6700. return false;
  6701. }
  6702. }
  6703. }
  6704. catch (e) {
  6705. // Global protection
  6706. }
  6707. return false;
  6708. };
  6709. /**
  6710. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6711. * Be aware Math.random() could cause collisions, but:
  6712. * "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"
  6713. */
  6714. Tools.RandomId = function () {
  6715. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6716. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6717. return v.toString(16);
  6718. });
  6719. };
  6720. Object.defineProperty(Tools, "NoneLogLevel", {
  6721. get: function () {
  6722. return Tools._NoneLogLevel;
  6723. },
  6724. enumerable: true,
  6725. configurable: true
  6726. });
  6727. Object.defineProperty(Tools, "MessageLogLevel", {
  6728. get: function () {
  6729. return Tools._MessageLogLevel;
  6730. },
  6731. enumerable: true,
  6732. configurable: true
  6733. });
  6734. Object.defineProperty(Tools, "WarningLogLevel", {
  6735. get: function () {
  6736. return Tools._WarningLogLevel;
  6737. },
  6738. enumerable: true,
  6739. configurable: true
  6740. });
  6741. Object.defineProperty(Tools, "ErrorLogLevel", {
  6742. get: function () {
  6743. return Tools._ErrorLogLevel;
  6744. },
  6745. enumerable: true,
  6746. configurable: true
  6747. });
  6748. Object.defineProperty(Tools, "AllLogLevel", {
  6749. get: function () {
  6750. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6751. },
  6752. enumerable: true,
  6753. configurable: true
  6754. });
  6755. Tools._AddLogEntry = function (entry) {
  6756. Tools._LogCache = entry + Tools._LogCache;
  6757. if (Tools.OnNewCacheEntry) {
  6758. Tools.OnNewCacheEntry(entry);
  6759. }
  6760. };
  6761. Tools._FormatMessage = function (message) {
  6762. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6763. var date = new Date();
  6764. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6765. };
  6766. Tools._LogDisabled = function (message) {
  6767. // nothing to do
  6768. };
  6769. Tools._LogEnabled = function (message) {
  6770. var formattedMessage = Tools._FormatMessage(message);
  6771. console.log("BJS - " + formattedMessage);
  6772. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6773. Tools._AddLogEntry(entry);
  6774. };
  6775. Tools._WarnDisabled = function (message) {
  6776. // nothing to do
  6777. };
  6778. Tools._WarnEnabled = function (message) {
  6779. var formattedMessage = Tools._FormatMessage(message);
  6780. console.warn("BJS - " + formattedMessage);
  6781. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6782. Tools._AddLogEntry(entry);
  6783. };
  6784. Tools._ErrorDisabled = function (message) {
  6785. // nothing to do
  6786. };
  6787. Tools._ErrorEnabled = function (message) {
  6788. Tools.errorsCount++;
  6789. var formattedMessage = Tools._FormatMessage(message);
  6790. console.error("BJS - " + formattedMessage);
  6791. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6792. Tools._AddLogEntry(entry);
  6793. };
  6794. Object.defineProperty(Tools, "LogCache", {
  6795. get: function () {
  6796. return Tools._LogCache;
  6797. },
  6798. enumerable: true,
  6799. configurable: true
  6800. });
  6801. Tools.ClearLogCache = function () {
  6802. Tools._LogCache = "";
  6803. Tools.errorsCount = 0;
  6804. };
  6805. Object.defineProperty(Tools, "LogLevels", {
  6806. set: function (level) {
  6807. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6808. Tools.Log = Tools._LogEnabled;
  6809. }
  6810. else {
  6811. Tools.Log = Tools._LogDisabled;
  6812. }
  6813. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6814. Tools.Warn = Tools._WarnEnabled;
  6815. }
  6816. else {
  6817. Tools.Warn = Tools._WarnDisabled;
  6818. }
  6819. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6820. Tools.Error = Tools._ErrorEnabled;
  6821. }
  6822. else {
  6823. Tools.Error = Tools._ErrorDisabled;
  6824. }
  6825. },
  6826. enumerable: true,
  6827. configurable: true
  6828. });
  6829. Tools.IsWindowObjectExist = function () {
  6830. return (typeof window) !== "undefined";
  6831. };
  6832. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6833. get: function () {
  6834. return Tools._PerformanceNoneLogLevel;
  6835. },
  6836. enumerable: true,
  6837. configurable: true
  6838. });
  6839. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6840. get: function () {
  6841. return Tools._PerformanceUserMarkLogLevel;
  6842. },
  6843. enumerable: true,
  6844. configurable: true
  6845. });
  6846. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6847. get: function () {
  6848. return Tools._PerformanceConsoleLogLevel;
  6849. },
  6850. enumerable: true,
  6851. configurable: true
  6852. });
  6853. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6854. set: function (level) {
  6855. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6856. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6857. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6858. return;
  6859. }
  6860. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6861. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6862. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6863. return;
  6864. }
  6865. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6866. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6867. },
  6868. enumerable: true,
  6869. configurable: true
  6870. });
  6871. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6872. };
  6873. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6874. };
  6875. Tools._StartUserMark = function (counterName, condition) {
  6876. if (condition === void 0) { condition = true; }
  6877. if (!Tools._performance) {
  6878. if (!Tools.IsWindowObjectExist()) {
  6879. return;
  6880. }
  6881. Tools._performance = window.performance;
  6882. }
  6883. if (!condition || !Tools._performance.mark) {
  6884. return;
  6885. }
  6886. Tools._performance.mark(counterName + "-Begin");
  6887. };
  6888. Tools._EndUserMark = function (counterName, condition) {
  6889. if (condition === void 0) { condition = true; }
  6890. if (!condition || !Tools._performance.mark) {
  6891. return;
  6892. }
  6893. Tools._performance.mark(counterName + "-End");
  6894. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6895. };
  6896. Tools._StartPerformanceConsole = function (counterName, condition) {
  6897. if (condition === void 0) { condition = true; }
  6898. if (!condition) {
  6899. return;
  6900. }
  6901. Tools._StartUserMark(counterName, condition);
  6902. if (console.time) {
  6903. console.time(counterName);
  6904. }
  6905. };
  6906. Tools._EndPerformanceConsole = function (counterName, condition) {
  6907. if (condition === void 0) { condition = true; }
  6908. if (!condition) {
  6909. return;
  6910. }
  6911. Tools._EndUserMark(counterName, condition);
  6912. if (console.time) {
  6913. console.timeEnd(counterName);
  6914. }
  6915. };
  6916. Object.defineProperty(Tools, "Now", {
  6917. get: function () {
  6918. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  6919. return window.performance.now();
  6920. }
  6921. return new Date().getTime();
  6922. },
  6923. enumerable: true,
  6924. configurable: true
  6925. });
  6926. /**
  6927. * This method will return the name of the class used to create the instance of the given object.
  6928. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6929. * @param object the object to get the class name from
  6930. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6931. */
  6932. Tools.GetClassName = function (object, isType) {
  6933. if (isType === void 0) { isType = false; }
  6934. var name = null;
  6935. if (!isType && object.getClassName) {
  6936. name = object.getClassName();
  6937. }
  6938. else {
  6939. if (object instanceof Object) {
  6940. var classObj = isType ? object : Object.getPrototypeOf(object);
  6941. name = classObj.constructor["__bjsclassName__"];
  6942. }
  6943. if (!name) {
  6944. name = typeof object;
  6945. }
  6946. }
  6947. return name;
  6948. };
  6949. Tools.First = function (array, predicate) {
  6950. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6951. var el = array_1[_i];
  6952. if (predicate(el)) {
  6953. return el;
  6954. }
  6955. }
  6956. return null;
  6957. };
  6958. /**
  6959. * This method will return the name of the full name of the class, including its owning module (if any).
  6960. * 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).
  6961. * @param object the object to get the class name from
  6962. * @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.
  6963. */
  6964. Tools.getFullClassName = function (object, isType) {
  6965. if (isType === void 0) { isType = false; }
  6966. var className = null;
  6967. var moduleName = null;
  6968. if (!isType && object.getClassName) {
  6969. className = object.getClassName();
  6970. }
  6971. else {
  6972. if (object instanceof Object) {
  6973. var classObj = isType ? object : Object.getPrototypeOf(object);
  6974. className = classObj.constructor["__bjsclassName__"];
  6975. moduleName = classObj.constructor["__bjsmoduleName__"];
  6976. }
  6977. if (!className) {
  6978. className = typeof object;
  6979. }
  6980. }
  6981. if (!className) {
  6982. return null;
  6983. }
  6984. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6985. };
  6986. /**
  6987. * 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.
  6988. * @param array
  6989. */
  6990. Tools.arrayOrStringFeeder = function (array) {
  6991. return function (index) {
  6992. if (index >= array.length) {
  6993. return null;
  6994. }
  6995. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6996. if (val && val.getHashCode) {
  6997. val = val.getHashCode();
  6998. }
  6999. if (typeof val === "string") {
  7000. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  7001. }
  7002. return val;
  7003. };
  7004. };
  7005. /**
  7006. * Compute the hashCode of a stream of number
  7007. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  7008. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  7009. * @return the hash code computed
  7010. */
  7011. Tools.hashCodeFromStream = function (feeder) {
  7012. // Based from here: http://stackoverflow.com/a/7616484/802124
  7013. var hash = 0;
  7014. var index = 0;
  7015. var chr = feeder(index++);
  7016. while (chr != null) {
  7017. hash = ((hash << 5) - hash) + chr;
  7018. hash |= 0; // Convert to 32bit integer
  7019. chr = feeder(index++);
  7020. }
  7021. return hash;
  7022. };
  7023. Tools.BaseUrl = "";
  7024. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  7025. /**
  7026. * Default behaviour for cors in the application.
  7027. * It can be a string if the expected behavior is identical in the entire app.
  7028. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  7029. */
  7030. Tools.CorsBehavior = "anonymous";
  7031. Tools.UseFallbackTexture = true;
  7032. /**
  7033. * Use this object to register external classes like custom textures or material
  7034. * to allow the laoders to instantiate them
  7035. */
  7036. Tools.RegisteredExternalClasses = {};
  7037. // Used in case of a texture loading problem
  7038. 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";
  7039. Tools.PreprocessUrl = function (url) {
  7040. return url;
  7041. };
  7042. // Logs
  7043. Tools._NoneLogLevel = 0;
  7044. Tools._MessageLogLevel = 1;
  7045. Tools._WarningLogLevel = 2;
  7046. Tools._ErrorLogLevel = 4;
  7047. Tools._LogCache = "";
  7048. Tools.errorsCount = 0;
  7049. Tools.Log = Tools._LogEnabled;
  7050. Tools.Warn = Tools._WarnEnabled;
  7051. Tools.Error = Tools._ErrorEnabled;
  7052. // Performances
  7053. Tools._PerformanceNoneLogLevel = 0;
  7054. Tools._PerformanceUserMarkLogLevel = 1;
  7055. Tools._PerformanceConsoleLogLevel = 2;
  7056. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7057. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7058. return Tools;
  7059. }());
  7060. BABYLON.Tools = Tools;
  7061. /**
  7062. * This class is used to track a performance counter which is number based.
  7063. * The user has access to many properties which give statistics of different nature
  7064. *
  7065. * The implementer can track two kinds of Performance Counter: time and count
  7066. * 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.
  7067. * 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.
  7068. */
  7069. var PerfCounter = /** @class */ (function () {
  7070. function PerfCounter() {
  7071. this._startMonitoringTime = 0;
  7072. this._min = 0;
  7073. this._max = 0;
  7074. this._average = 0;
  7075. this._lastSecAverage = 0;
  7076. this._current = 0;
  7077. this._totalValueCount = 0;
  7078. this._totalAccumulated = 0;
  7079. this._lastSecAccumulated = 0;
  7080. this._lastSecTime = 0;
  7081. this._lastSecValueCount = 0;
  7082. }
  7083. Object.defineProperty(PerfCounter.prototype, "min", {
  7084. /**
  7085. * Returns the smallest value ever
  7086. */
  7087. get: function () {
  7088. return this._min;
  7089. },
  7090. enumerable: true,
  7091. configurable: true
  7092. });
  7093. Object.defineProperty(PerfCounter.prototype, "max", {
  7094. /**
  7095. * Returns the biggest value ever
  7096. */
  7097. get: function () {
  7098. return this._max;
  7099. },
  7100. enumerable: true,
  7101. configurable: true
  7102. });
  7103. Object.defineProperty(PerfCounter.prototype, "average", {
  7104. /**
  7105. * Returns the average value since the performance counter is running
  7106. */
  7107. get: function () {
  7108. return this._average;
  7109. },
  7110. enumerable: true,
  7111. configurable: true
  7112. });
  7113. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  7114. /**
  7115. * Returns the average value of the last second the counter was monitored
  7116. */
  7117. get: function () {
  7118. return this._lastSecAverage;
  7119. },
  7120. enumerable: true,
  7121. configurable: true
  7122. });
  7123. Object.defineProperty(PerfCounter.prototype, "current", {
  7124. /**
  7125. * Returns the current value
  7126. */
  7127. get: function () {
  7128. return this._current;
  7129. },
  7130. enumerable: true,
  7131. configurable: true
  7132. });
  7133. Object.defineProperty(PerfCounter.prototype, "total", {
  7134. get: function () {
  7135. return this._totalAccumulated;
  7136. },
  7137. enumerable: true,
  7138. configurable: true
  7139. });
  7140. Object.defineProperty(PerfCounter.prototype, "count", {
  7141. get: function () {
  7142. return this._totalValueCount;
  7143. },
  7144. enumerable: true,
  7145. configurable: true
  7146. });
  7147. /**
  7148. * Call this method to start monitoring a new frame.
  7149. * 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.
  7150. */
  7151. PerfCounter.prototype.fetchNewFrame = function () {
  7152. this._totalValueCount++;
  7153. this._current = 0;
  7154. this._lastSecValueCount++;
  7155. };
  7156. /**
  7157. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  7158. * @param newCount the count value to add to the monitored count
  7159. * @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.
  7160. */
  7161. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  7162. if (!PerfCounter.Enabled) {
  7163. return;
  7164. }
  7165. this._current += newCount;
  7166. if (fetchResult) {
  7167. this._fetchResult();
  7168. }
  7169. };
  7170. /**
  7171. * Start monitoring this performance counter
  7172. */
  7173. PerfCounter.prototype.beginMonitoring = function () {
  7174. if (!PerfCounter.Enabled) {
  7175. return;
  7176. }
  7177. this._startMonitoringTime = Tools.Now;
  7178. };
  7179. /**
  7180. * Compute the time lapsed since the previous beginMonitoring() call.
  7181. * @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
  7182. */
  7183. PerfCounter.prototype.endMonitoring = function (newFrame) {
  7184. if (newFrame === void 0) { newFrame = true; }
  7185. if (!PerfCounter.Enabled) {
  7186. return;
  7187. }
  7188. if (newFrame) {
  7189. this.fetchNewFrame();
  7190. }
  7191. var currentTime = Tools.Now;
  7192. this._current = currentTime - this._startMonitoringTime;
  7193. if (newFrame) {
  7194. this._fetchResult();
  7195. }
  7196. };
  7197. PerfCounter.prototype._fetchResult = function () {
  7198. this._totalAccumulated += this._current;
  7199. this._lastSecAccumulated += this._current;
  7200. // Min/Max update
  7201. this._min = Math.min(this._min, this._current);
  7202. this._max = Math.max(this._max, this._current);
  7203. this._average = this._totalAccumulated / this._totalValueCount;
  7204. // Reset last sec?
  7205. var now = Tools.Now;
  7206. if ((now - this._lastSecTime) > 1000) {
  7207. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  7208. this._lastSecTime = now;
  7209. this._lastSecAccumulated = 0;
  7210. this._lastSecValueCount = 0;
  7211. }
  7212. };
  7213. PerfCounter.Enabled = true;
  7214. return PerfCounter;
  7215. }());
  7216. BABYLON.PerfCounter = PerfCounter;
  7217. /**
  7218. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  7219. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  7220. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  7221. * @param name The name of the class, case should be preserved
  7222. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  7223. */
  7224. function className(name, module) {
  7225. return function (target) {
  7226. target["__bjsclassName__"] = name;
  7227. target["__bjsmoduleName__"] = (module != null) ? module : null;
  7228. };
  7229. }
  7230. BABYLON.className = className;
  7231. /**
  7232. * An implementation of a loop for asynchronous functions.
  7233. */
  7234. var AsyncLoop = /** @class */ (function () {
  7235. /**
  7236. * Constroctor.
  7237. * @param iterations the number of iterations.
  7238. * @param _fn the function to run each iteration
  7239. * @param _successCallback the callback that will be called upon succesful execution
  7240. * @param offset starting offset.
  7241. */
  7242. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  7243. if (offset === void 0) { offset = 0; }
  7244. this.iterations = iterations;
  7245. this._fn = _fn;
  7246. this._successCallback = _successCallback;
  7247. this.index = offset - 1;
  7248. this._done = false;
  7249. }
  7250. /**
  7251. * Execute the next iteration. Must be called after the last iteration was finished.
  7252. */
  7253. AsyncLoop.prototype.executeNext = function () {
  7254. if (!this._done) {
  7255. if (this.index + 1 < this.iterations) {
  7256. ++this.index;
  7257. this._fn(this);
  7258. }
  7259. else {
  7260. this.breakLoop();
  7261. }
  7262. }
  7263. };
  7264. /**
  7265. * Break the loop and run the success callback.
  7266. */
  7267. AsyncLoop.prototype.breakLoop = function () {
  7268. this._done = true;
  7269. this._successCallback();
  7270. };
  7271. /**
  7272. * Helper function
  7273. */
  7274. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  7275. if (offset === void 0) { offset = 0; }
  7276. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  7277. loop.executeNext();
  7278. return loop;
  7279. };
  7280. /**
  7281. * A for-loop that will run a given number of iterations synchronous and the rest async.
  7282. * @param iterations total number of iterations
  7283. * @param syncedIterations number of synchronous iterations in each async iteration.
  7284. * @param fn the function to call each iteration.
  7285. * @param callback a success call back that will be called when iterating stops.
  7286. * @param breakFunction a break condition (optional)
  7287. * @param timeout timeout settings for the setTimeout function. default - 0.
  7288. * @constructor
  7289. */
  7290. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  7291. if (timeout === void 0) { timeout = 0; }
  7292. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  7293. if (breakFunction && breakFunction())
  7294. loop.breakLoop();
  7295. else {
  7296. setTimeout(function () {
  7297. for (var i = 0; i < syncedIterations; ++i) {
  7298. var iteration = (loop.index * syncedIterations) + i;
  7299. if (iteration >= iterations)
  7300. break;
  7301. fn(iteration);
  7302. if (breakFunction && breakFunction()) {
  7303. loop.breakLoop();
  7304. break;
  7305. }
  7306. }
  7307. loop.executeNext();
  7308. }, timeout);
  7309. }
  7310. }, callback);
  7311. };
  7312. return AsyncLoop;
  7313. }());
  7314. BABYLON.AsyncLoop = AsyncLoop;
  7315. })(BABYLON || (BABYLON = {}));
  7316. //# sourceMappingURL=babylon.tools.js.map
  7317. var BABYLON;
  7318. (function (BABYLON) {
  7319. var Internals;
  7320. (function (Internals) {
  7321. var _AlphaState = /** @class */ (function () {
  7322. /**
  7323. * Initializes the state.
  7324. */
  7325. function _AlphaState() {
  7326. this._isAlphaBlendDirty = false;
  7327. this._isBlendFunctionParametersDirty = false;
  7328. this._isBlendEquationParametersDirty = false;
  7329. this._isBlendConstantsDirty = false;
  7330. this._alphaBlend = false;
  7331. this._blendFunctionParameters = new Array(4);
  7332. this._blendEquationParameters = new Array(2);
  7333. this._blendConstants = new Array(4);
  7334. this.reset();
  7335. }
  7336. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  7337. get: function () {
  7338. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  7339. },
  7340. enumerable: true,
  7341. configurable: true
  7342. });
  7343. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  7344. get: function () {
  7345. return this._alphaBlend;
  7346. },
  7347. set: function (value) {
  7348. if (this._alphaBlend === value) {
  7349. return;
  7350. }
  7351. this._alphaBlend = value;
  7352. this._isAlphaBlendDirty = true;
  7353. },
  7354. enumerable: true,
  7355. configurable: true
  7356. });
  7357. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  7358. if (this._blendConstants[0] === r &&
  7359. this._blendConstants[1] === g &&
  7360. this._blendConstants[2] === b &&
  7361. this._blendConstants[3] === a) {
  7362. return;
  7363. }
  7364. this._blendConstants[0] = r;
  7365. this._blendConstants[1] = g;
  7366. this._blendConstants[2] = b;
  7367. this._blendConstants[3] = a;
  7368. this._isBlendConstantsDirty = true;
  7369. };
  7370. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  7371. if (this._blendFunctionParameters[0] === value0 &&
  7372. this._blendFunctionParameters[1] === value1 &&
  7373. this._blendFunctionParameters[2] === value2 &&
  7374. this._blendFunctionParameters[3] === value3) {
  7375. return;
  7376. }
  7377. this._blendFunctionParameters[0] = value0;
  7378. this._blendFunctionParameters[1] = value1;
  7379. this._blendFunctionParameters[2] = value2;
  7380. this._blendFunctionParameters[3] = value3;
  7381. this._isBlendFunctionParametersDirty = true;
  7382. };
  7383. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  7384. if (this._blendEquationParameters[0] === rgb &&
  7385. this._blendEquationParameters[1] === alpha) {
  7386. return;
  7387. }
  7388. this._blendEquationParameters[0] = rgb;
  7389. this._blendEquationParameters[1] = alpha;
  7390. this._isBlendEquationParametersDirty = true;
  7391. };
  7392. _AlphaState.prototype.reset = function () {
  7393. this._alphaBlend = false;
  7394. this._blendFunctionParameters[0] = null;
  7395. this._blendFunctionParameters[1] = null;
  7396. this._blendFunctionParameters[2] = null;
  7397. this._blendFunctionParameters[3] = null;
  7398. this._blendEquationParameters[0] = null;
  7399. this._blendEquationParameters[1] = null;
  7400. this._blendConstants[0] = null;
  7401. this._blendConstants[1] = null;
  7402. this._blendConstants[2] = null;
  7403. this._blendConstants[3] = null;
  7404. this._isAlphaBlendDirty = true;
  7405. this._isBlendFunctionParametersDirty = false;
  7406. this._isBlendEquationParametersDirty = false;
  7407. this._isBlendConstantsDirty = false;
  7408. };
  7409. _AlphaState.prototype.apply = function (gl) {
  7410. if (!this.isDirty) {
  7411. return;
  7412. }
  7413. // Alpha blend
  7414. if (this._isAlphaBlendDirty) {
  7415. if (this._alphaBlend) {
  7416. gl.enable(gl.BLEND);
  7417. }
  7418. else {
  7419. gl.disable(gl.BLEND);
  7420. }
  7421. this._isAlphaBlendDirty = false;
  7422. }
  7423. // Alpha function
  7424. if (this._isBlendFunctionParametersDirty) {
  7425. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  7426. this._isBlendFunctionParametersDirty = false;
  7427. }
  7428. // Alpha equation
  7429. if (this._isBlendEquationParametersDirty) {
  7430. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  7431. this._isBlendEquationParametersDirty = false;
  7432. }
  7433. // Constants
  7434. if (this._isBlendConstantsDirty) {
  7435. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  7436. this._isBlendConstantsDirty = false;
  7437. }
  7438. };
  7439. return _AlphaState;
  7440. }());
  7441. Internals._AlphaState = _AlphaState;
  7442. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7443. })(BABYLON || (BABYLON = {}));
  7444. //# sourceMappingURL=babylon.alphaCullingState.js.map
  7445. var BABYLON;
  7446. (function (BABYLON) {
  7447. var Internals;
  7448. (function (Internals) {
  7449. var _DepthCullingState = /** @class */ (function () {
  7450. /**
  7451. * Initializes the state.
  7452. */
  7453. function _DepthCullingState() {
  7454. this._isDepthTestDirty = false;
  7455. this._isDepthMaskDirty = false;
  7456. this._isDepthFuncDirty = false;
  7457. this._isCullFaceDirty = false;
  7458. this._isCullDirty = false;
  7459. this._isZOffsetDirty = false;
  7460. this._isFrontFaceDirty = false;
  7461. this.reset();
  7462. }
  7463. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  7464. get: function () {
  7465. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  7466. },
  7467. enumerable: true,
  7468. configurable: true
  7469. });
  7470. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  7471. get: function () {
  7472. return this._zOffset;
  7473. },
  7474. set: function (value) {
  7475. if (this._zOffset === value) {
  7476. return;
  7477. }
  7478. this._zOffset = value;
  7479. this._isZOffsetDirty = true;
  7480. },
  7481. enumerable: true,
  7482. configurable: true
  7483. });
  7484. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  7485. get: function () {
  7486. return this._cullFace;
  7487. },
  7488. set: function (value) {
  7489. if (this._cullFace === value) {
  7490. return;
  7491. }
  7492. this._cullFace = value;
  7493. this._isCullFaceDirty = true;
  7494. },
  7495. enumerable: true,
  7496. configurable: true
  7497. });
  7498. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  7499. get: function () {
  7500. return this._cull;
  7501. },
  7502. set: function (value) {
  7503. if (this._cull === value) {
  7504. return;
  7505. }
  7506. this._cull = value;
  7507. this._isCullDirty = true;
  7508. },
  7509. enumerable: true,
  7510. configurable: true
  7511. });
  7512. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  7513. get: function () {
  7514. return this._depthFunc;
  7515. },
  7516. set: function (value) {
  7517. if (this._depthFunc === value) {
  7518. return;
  7519. }
  7520. this._depthFunc = value;
  7521. this._isDepthFuncDirty = true;
  7522. },
  7523. enumerable: true,
  7524. configurable: true
  7525. });
  7526. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  7527. get: function () {
  7528. return this._depthMask;
  7529. },
  7530. set: function (value) {
  7531. if (this._depthMask === value) {
  7532. return;
  7533. }
  7534. this._depthMask = value;
  7535. this._isDepthMaskDirty = true;
  7536. },
  7537. enumerable: true,
  7538. configurable: true
  7539. });
  7540. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  7541. get: function () {
  7542. return this._depthTest;
  7543. },
  7544. set: function (value) {
  7545. if (this._depthTest === value) {
  7546. return;
  7547. }
  7548. this._depthTest = value;
  7549. this._isDepthTestDirty = true;
  7550. },
  7551. enumerable: true,
  7552. configurable: true
  7553. });
  7554. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  7555. get: function () {
  7556. return this._frontFace;
  7557. },
  7558. set: function (value) {
  7559. if (this._frontFace === value) {
  7560. return;
  7561. }
  7562. this._frontFace = value;
  7563. this._isFrontFaceDirty = true;
  7564. },
  7565. enumerable: true,
  7566. configurable: true
  7567. });
  7568. _DepthCullingState.prototype.reset = function () {
  7569. this._depthMask = true;
  7570. this._depthTest = true;
  7571. this._depthFunc = null;
  7572. this._cullFace = null;
  7573. this._cull = null;
  7574. this._zOffset = 0;
  7575. this._frontFace = null;
  7576. this._isDepthTestDirty = true;
  7577. this._isDepthMaskDirty = true;
  7578. this._isDepthFuncDirty = false;
  7579. this._isCullFaceDirty = false;
  7580. this._isCullDirty = false;
  7581. this._isZOffsetDirty = false;
  7582. this._isFrontFaceDirty = false;
  7583. };
  7584. _DepthCullingState.prototype.apply = function (gl) {
  7585. if (!this.isDirty) {
  7586. return;
  7587. }
  7588. // Cull
  7589. if (this._isCullDirty) {
  7590. if (this.cull) {
  7591. gl.enable(gl.CULL_FACE);
  7592. }
  7593. else {
  7594. gl.disable(gl.CULL_FACE);
  7595. }
  7596. this._isCullDirty = false;
  7597. }
  7598. // Cull face
  7599. if (this._isCullFaceDirty) {
  7600. gl.cullFace(this.cullFace);
  7601. this._isCullFaceDirty = false;
  7602. }
  7603. // Depth mask
  7604. if (this._isDepthMaskDirty) {
  7605. gl.depthMask(this.depthMask);
  7606. this._isDepthMaskDirty = false;
  7607. }
  7608. // Depth test
  7609. if (this._isDepthTestDirty) {
  7610. if (this.depthTest) {
  7611. gl.enable(gl.DEPTH_TEST);
  7612. }
  7613. else {
  7614. gl.disable(gl.DEPTH_TEST);
  7615. }
  7616. this._isDepthTestDirty = false;
  7617. }
  7618. // Depth func
  7619. if (this._isDepthFuncDirty) {
  7620. gl.depthFunc(this.depthFunc);
  7621. this._isDepthFuncDirty = false;
  7622. }
  7623. // zOffset
  7624. if (this._isZOffsetDirty) {
  7625. if (this.zOffset) {
  7626. gl.enable(gl.POLYGON_OFFSET_FILL);
  7627. gl.polygonOffset(this.zOffset, 0);
  7628. }
  7629. else {
  7630. gl.disable(gl.POLYGON_OFFSET_FILL);
  7631. }
  7632. this._isZOffsetDirty = false;
  7633. }
  7634. // Front face
  7635. if (this._isFrontFaceDirty) {
  7636. gl.frontFace(this.frontFace);
  7637. this._isFrontFaceDirty = false;
  7638. }
  7639. };
  7640. return _DepthCullingState;
  7641. }());
  7642. Internals._DepthCullingState = _DepthCullingState;
  7643. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7644. })(BABYLON || (BABYLON = {}));
  7645. //# sourceMappingURL=babylon.depthCullingState.js.map
  7646. var BABYLON;
  7647. (function (BABYLON) {
  7648. var Internals;
  7649. (function (Internals) {
  7650. var _StencilState = /** @class */ (function () {
  7651. function _StencilState() {
  7652. this._isStencilTestDirty = false;
  7653. this._isStencilMaskDirty = false;
  7654. this._isStencilFuncDirty = false;
  7655. this._isStencilOpDirty = false;
  7656. this.reset();
  7657. }
  7658. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7659. get: function () {
  7660. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7661. },
  7662. enumerable: true,
  7663. configurable: true
  7664. });
  7665. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7666. get: function () {
  7667. return this._stencilFunc;
  7668. },
  7669. set: function (value) {
  7670. if (this._stencilFunc === value) {
  7671. return;
  7672. }
  7673. this._stencilFunc = value;
  7674. this._isStencilFuncDirty = true;
  7675. },
  7676. enumerable: true,
  7677. configurable: true
  7678. });
  7679. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7680. get: function () {
  7681. return this._stencilFuncRef;
  7682. },
  7683. set: function (value) {
  7684. if (this._stencilFuncRef === value) {
  7685. return;
  7686. }
  7687. this._stencilFuncRef = value;
  7688. this._isStencilFuncDirty = true;
  7689. },
  7690. enumerable: true,
  7691. configurable: true
  7692. });
  7693. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7694. get: function () {
  7695. return this._stencilFuncMask;
  7696. },
  7697. set: function (value) {
  7698. if (this._stencilFuncMask === value) {
  7699. return;
  7700. }
  7701. this._stencilFuncMask = value;
  7702. this._isStencilFuncDirty = true;
  7703. },
  7704. enumerable: true,
  7705. configurable: true
  7706. });
  7707. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7708. get: function () {
  7709. return this._stencilOpStencilFail;
  7710. },
  7711. set: function (value) {
  7712. if (this._stencilOpStencilFail === value) {
  7713. return;
  7714. }
  7715. this._stencilOpStencilFail = value;
  7716. this._isStencilOpDirty = true;
  7717. },
  7718. enumerable: true,
  7719. configurable: true
  7720. });
  7721. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7722. get: function () {
  7723. return this._stencilOpDepthFail;
  7724. },
  7725. set: function (value) {
  7726. if (this._stencilOpDepthFail === value) {
  7727. return;
  7728. }
  7729. this._stencilOpDepthFail = value;
  7730. this._isStencilOpDirty = true;
  7731. },
  7732. enumerable: true,
  7733. configurable: true
  7734. });
  7735. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7736. get: function () {
  7737. return this._stencilOpStencilDepthPass;
  7738. },
  7739. set: function (value) {
  7740. if (this._stencilOpStencilDepthPass === value) {
  7741. return;
  7742. }
  7743. this._stencilOpStencilDepthPass = value;
  7744. this._isStencilOpDirty = true;
  7745. },
  7746. enumerable: true,
  7747. configurable: true
  7748. });
  7749. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7750. get: function () {
  7751. return this._stencilMask;
  7752. },
  7753. set: function (value) {
  7754. if (this._stencilMask === value) {
  7755. return;
  7756. }
  7757. this._stencilMask = value;
  7758. this._isStencilMaskDirty = true;
  7759. },
  7760. enumerable: true,
  7761. configurable: true
  7762. });
  7763. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7764. get: function () {
  7765. return this._stencilTest;
  7766. },
  7767. set: function (value) {
  7768. if (this._stencilTest === value) {
  7769. return;
  7770. }
  7771. this._stencilTest = value;
  7772. this._isStencilTestDirty = true;
  7773. },
  7774. enumerable: true,
  7775. configurable: true
  7776. });
  7777. _StencilState.prototype.reset = function () {
  7778. this._stencilTest = false;
  7779. this._stencilMask = 0xFF;
  7780. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7781. this._stencilFuncRef = 1;
  7782. this._stencilFuncMask = 0xFF;
  7783. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7784. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7785. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7786. this._isStencilTestDirty = true;
  7787. this._isStencilMaskDirty = true;
  7788. this._isStencilFuncDirty = true;
  7789. this._isStencilOpDirty = true;
  7790. };
  7791. _StencilState.prototype.apply = function (gl) {
  7792. if (!this.isDirty) {
  7793. return;
  7794. }
  7795. // Stencil test
  7796. if (this._isStencilTestDirty) {
  7797. if (this.stencilTest) {
  7798. gl.enable(gl.STENCIL_TEST);
  7799. }
  7800. else {
  7801. gl.disable(gl.STENCIL_TEST);
  7802. }
  7803. this._isStencilTestDirty = false;
  7804. }
  7805. // Stencil mask
  7806. if (this._isStencilMaskDirty) {
  7807. gl.stencilMask(this.stencilMask);
  7808. this._isStencilMaskDirty = false;
  7809. }
  7810. // Stencil func
  7811. if (this._isStencilFuncDirty) {
  7812. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7813. this._isStencilFuncDirty = false;
  7814. }
  7815. // Stencil op
  7816. if (this._isStencilOpDirty) {
  7817. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7818. this._isStencilOpDirty = false;
  7819. }
  7820. };
  7821. return _StencilState;
  7822. }());
  7823. Internals._StencilState = _StencilState;
  7824. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7825. })(BABYLON || (BABYLON = {}));
  7826. //# sourceMappingURL=babylon.stencilState.js.map
  7827. var BABYLON;
  7828. (function (BABYLON) {
  7829. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7830. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  7831. };
  7832. var compileRawShader = function (gl, source, type) {
  7833. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7834. gl.shaderSource(shader, source);
  7835. gl.compileShader(shader);
  7836. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7837. var log = gl.getShaderInfoLog(shader);
  7838. if (log) {
  7839. throw new Error(log);
  7840. }
  7841. }
  7842. if (!shader) {
  7843. throw new Error("Something went wrong while compile the shader.");
  7844. }
  7845. return shader;
  7846. };
  7847. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7848. var magFilter = gl.NEAREST;
  7849. var minFilter = gl.NEAREST;
  7850. switch (samplingMode) {
  7851. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  7852. magFilter = gl.LINEAR;
  7853. if (generateMipMaps) {
  7854. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7855. }
  7856. else {
  7857. minFilter = gl.LINEAR;
  7858. }
  7859. break;
  7860. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  7861. magFilter = gl.LINEAR;
  7862. if (generateMipMaps) {
  7863. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7864. }
  7865. else {
  7866. minFilter = gl.LINEAR;
  7867. }
  7868. break;
  7869. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  7870. magFilter = gl.NEAREST;
  7871. if (generateMipMaps) {
  7872. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7873. }
  7874. else {
  7875. minFilter = gl.NEAREST;
  7876. }
  7877. break;
  7878. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  7879. magFilter = gl.NEAREST;
  7880. if (generateMipMaps) {
  7881. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7882. }
  7883. else {
  7884. minFilter = gl.NEAREST;
  7885. }
  7886. break;
  7887. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  7888. magFilter = gl.NEAREST;
  7889. if (generateMipMaps) {
  7890. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7891. }
  7892. else {
  7893. minFilter = gl.LINEAR;
  7894. }
  7895. break;
  7896. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  7897. magFilter = gl.NEAREST;
  7898. if (generateMipMaps) {
  7899. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7900. }
  7901. else {
  7902. minFilter = gl.LINEAR;
  7903. }
  7904. break;
  7905. case BABYLON.Texture.NEAREST_LINEAR:
  7906. magFilter = gl.NEAREST;
  7907. minFilter = gl.LINEAR;
  7908. break;
  7909. case BABYLON.Texture.NEAREST_NEAREST:
  7910. magFilter = gl.NEAREST;
  7911. minFilter = gl.NEAREST;
  7912. break;
  7913. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  7914. magFilter = gl.LINEAR;
  7915. if (generateMipMaps) {
  7916. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7917. }
  7918. else {
  7919. minFilter = gl.NEAREST;
  7920. }
  7921. break;
  7922. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  7923. magFilter = gl.LINEAR;
  7924. if (generateMipMaps) {
  7925. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7926. }
  7927. else {
  7928. minFilter = gl.NEAREST;
  7929. }
  7930. break;
  7931. case BABYLON.Texture.LINEAR_LINEAR:
  7932. magFilter = gl.LINEAR;
  7933. minFilter = gl.LINEAR;
  7934. break;
  7935. case BABYLON.Texture.LINEAR_NEAREST:
  7936. magFilter = gl.LINEAR;
  7937. minFilter = gl.NEAREST;
  7938. break;
  7939. }
  7940. return {
  7941. min: minFilter,
  7942. mag: magFilter
  7943. };
  7944. };
  7945. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7946. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7947. var img;
  7948. var onload = function () {
  7949. loadedImages[index] = img;
  7950. loadedImages._internalCount++;
  7951. if (scene) {
  7952. scene._removePendingData(img);
  7953. }
  7954. if (loadedImages._internalCount === 6) {
  7955. onfinish(loadedImages);
  7956. }
  7957. };
  7958. var onerror = function (message, exception) {
  7959. if (scene) {
  7960. scene._removePendingData(img);
  7961. }
  7962. if (onErrorCallBack) {
  7963. onErrorCallBack(message, exception);
  7964. }
  7965. };
  7966. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  7967. if (scene) {
  7968. scene._addPendingData(img);
  7969. }
  7970. };
  7971. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  7972. if (onError === void 0) { onError = null; }
  7973. var loadedImages = [];
  7974. loadedImages._internalCount = 0;
  7975. for (var index = 0; index < 6; index++) {
  7976. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  7977. }
  7978. };
  7979. var BufferPointer = /** @class */ (function () {
  7980. function BufferPointer() {
  7981. }
  7982. return BufferPointer;
  7983. }());
  7984. var InstancingAttributeInfo = /** @class */ (function () {
  7985. function InstancingAttributeInfo() {
  7986. }
  7987. return InstancingAttributeInfo;
  7988. }());
  7989. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7990. /**
  7991. * Define options used to create a render target texture
  7992. */
  7993. var RenderTargetCreationOptions = /** @class */ (function () {
  7994. function RenderTargetCreationOptions() {
  7995. }
  7996. return RenderTargetCreationOptions;
  7997. }());
  7998. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  7999. /**
  8000. * Regroup several parameters relative to the browser in use
  8001. */
  8002. var EngineCapabilities = /** @class */ (function () {
  8003. function EngineCapabilities() {
  8004. }
  8005. return EngineCapabilities;
  8006. }());
  8007. BABYLON.EngineCapabilities = EngineCapabilities;
  8008. /**
  8009. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  8010. */
  8011. var Engine = /** @class */ (function () {
  8012. /**
  8013. * @constructor
  8014. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  8015. * @param {boolean} [antialias] - enable antialias
  8016. * @param options - further options to be sent to the getContext function
  8017. */
  8018. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  8019. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  8020. var _this = this;
  8021. // Public members
  8022. this.forcePOTTextures = false;
  8023. this.isFullscreen = false;
  8024. this.isPointerLock = false;
  8025. this.cullBackFaces = true;
  8026. this.renderEvenInBackground = true;
  8027. this.preventCacheWipeBetweenFrames = false;
  8028. // To enable/disable IDB support and avoid XHR on .manifest
  8029. this.enableOfflineSupport = false;
  8030. this.scenes = new Array();
  8031. this.postProcesses = new Array();
  8032. // Observables
  8033. /**
  8034. * Observable event triggered each time the rendering canvas is resized
  8035. */
  8036. this.onResizeObservable = new BABYLON.Observable();
  8037. /**
  8038. * Observable event triggered each time the canvas loses focus
  8039. */
  8040. this.onCanvasBlurObservable = new BABYLON.Observable();
  8041. /**
  8042. * Observable event triggered each time the canvas gains focus
  8043. */
  8044. this.onCanvasFocusObservable = new BABYLON.Observable();
  8045. /**
  8046. * Observable event triggered each time the canvas receives pointerout event
  8047. */
  8048. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  8049. /**
  8050. * Observable event triggered before each texture is initialized
  8051. */
  8052. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  8053. //WebVR
  8054. this._vrDisplay = undefined;
  8055. this._vrSupported = false;
  8056. this._vrExclusivePointerMode = false;
  8057. // Uniform buffers list
  8058. this.disableUniformBuffers = false;
  8059. this._uniformBuffers = new Array();
  8060. // Observables
  8061. /**
  8062. * Observable raised when the engine begins a new frame
  8063. */
  8064. this.onBeginFrameObservable = new BABYLON.Observable();
  8065. /**
  8066. * Observable raised when the engine ends the current frame
  8067. */
  8068. this.onEndFrameObservable = new BABYLON.Observable();
  8069. /**
  8070. * Observable raised when the engine is about to compile a shader
  8071. */
  8072. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  8073. /**
  8074. * Observable raised when the engine has jsut compiled a shader
  8075. */
  8076. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  8077. this._windowIsBackground = false;
  8078. this._webGLVersion = 1.0;
  8079. this._badOS = false;
  8080. this._badDesktopOS = false;
  8081. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  8082. this.onVRRequestPresentComplete = new BABYLON.Observable();
  8083. this.onVRRequestPresentStart = new BABYLON.Observable();
  8084. this._colorWrite = true;
  8085. this._drawCalls = new BABYLON.PerfCounter();
  8086. this._textureCollisions = new BABYLON.PerfCounter();
  8087. this._renderingQueueLaunched = false;
  8088. this._activeRenderLoops = new Array();
  8089. // Deterministic lockstepMaxSteps
  8090. this._deterministicLockstep = false;
  8091. this._lockstepMaxSteps = 4;
  8092. // Lost context
  8093. this.onContextLostObservable = new BABYLON.Observable();
  8094. this.onContextRestoredObservable = new BABYLON.Observable();
  8095. this._contextWasLost = false;
  8096. this._doNotHandleContextLost = false;
  8097. // FPS
  8098. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  8099. this._fps = 60;
  8100. this._deltaTime = 0;
  8101. /**
  8102. * Turn this value on if you want to pause FPS computation when in background
  8103. */
  8104. this.disablePerformanceMonitorInBackground = false;
  8105. // States
  8106. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  8107. this._stencilState = new BABYLON.Internals._StencilState();
  8108. this._alphaState = new BABYLON.Internals._AlphaState();
  8109. this._alphaMode = Engine.ALPHA_DISABLE;
  8110. // Cache
  8111. this._internalTexturesCache = new Array();
  8112. this._boundTexturesCache = {};
  8113. this._boundTexturesStack = new Array();
  8114. this._compiledEffects = {};
  8115. this._vertexAttribArraysEnabled = [];
  8116. this._uintIndicesCurrentlySet = false;
  8117. this._currentBoundBuffer = new Array();
  8118. this._currentBufferPointers = new Array();
  8119. this._currentInstanceLocations = new Array();
  8120. this._currentInstanceBuffers = new Array();
  8121. this._vaoRecordInProgress = false;
  8122. this._mustWipeVertexAttributes = false;
  8123. this._nextFreeTextureSlots = new Array();
  8124. this._activeRequests = new Array();
  8125. // Hardware supported Compressed Textures
  8126. this._texturesSupported = new Array();
  8127. this._onVRFullScreenTriggered = function () {
  8128. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  8129. //get the old size before we change
  8130. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  8131. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  8132. //get the width and height, change the render size
  8133. var leftEye = _this._vrDisplay.getEyeParameters('left');
  8134. _this.setHardwareScalingLevel(1);
  8135. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  8136. }
  8137. else {
  8138. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  8139. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  8140. }
  8141. };
  8142. this._boundUniforms = {};
  8143. var canvas = null;
  8144. Engine.Instances.push(this);
  8145. if (!canvasOrContext) {
  8146. return;
  8147. }
  8148. options = options || {};
  8149. if (canvasOrContext.getContext) {
  8150. canvas = canvasOrContext;
  8151. this._renderingCanvas = canvas;
  8152. if (antialias != null) {
  8153. options.antialias = antialias;
  8154. }
  8155. if (options.deterministicLockstep === undefined) {
  8156. options.deterministicLockstep = false;
  8157. }
  8158. if (options.lockstepMaxSteps === undefined) {
  8159. options.lockstepMaxSteps = 4;
  8160. }
  8161. if (options.preserveDrawingBuffer === undefined) {
  8162. options.preserveDrawingBuffer = false;
  8163. }
  8164. if (options.audioEngine === undefined) {
  8165. options.audioEngine = true;
  8166. }
  8167. if (options.stencil === undefined) {
  8168. options.stencil = true;
  8169. }
  8170. this._deterministicLockstep = options.deterministicLockstep;
  8171. this._lockstepMaxSteps = options.lockstepMaxSteps;
  8172. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  8173. // Exceptions
  8174. if (navigator && navigator.userAgent) {
  8175. var ua = navigator.userAgent;
  8176. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  8177. var exception = _a[_i];
  8178. var key = exception.key;
  8179. var targets = exception.targets;
  8180. if (ua.indexOf(key) > -1) {
  8181. if (exception.capture && exception.captureConstraint) {
  8182. var capture = exception.capture;
  8183. var constraint = exception.captureConstraint;
  8184. var regex = new RegExp(capture);
  8185. var matches = regex.exec(ua);
  8186. if (matches && matches.length > 0) {
  8187. var capturedValue = parseInt(matches[matches.length - 1]);
  8188. if (capturedValue >= constraint) {
  8189. continue;
  8190. }
  8191. }
  8192. }
  8193. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  8194. var target = targets_1[_b];
  8195. switch (target) {
  8196. case "uniformBuffer":
  8197. this.disableUniformBuffers = true;
  8198. break;
  8199. }
  8200. }
  8201. break;
  8202. }
  8203. }
  8204. }
  8205. // GL
  8206. if (!options.disableWebGL2Support) {
  8207. try {
  8208. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  8209. if (this._gl) {
  8210. this._webGLVersion = 2.0;
  8211. }
  8212. }
  8213. catch (e) {
  8214. // Do nothing
  8215. }
  8216. }
  8217. if (!this._gl) {
  8218. if (!canvas) {
  8219. throw new Error("The provided canvas is null or undefined.");
  8220. }
  8221. try {
  8222. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  8223. }
  8224. catch (e) {
  8225. throw new Error("WebGL not supported");
  8226. }
  8227. }
  8228. if (!this._gl) {
  8229. throw new Error("WebGL not supported");
  8230. }
  8231. this._onCanvasFocus = function () {
  8232. _this.onCanvasFocusObservable.notifyObservers(_this);
  8233. };
  8234. this._onCanvasBlur = function () {
  8235. _this.onCanvasBlurObservable.notifyObservers(_this);
  8236. };
  8237. canvas.addEventListener("focus", this._onCanvasFocus);
  8238. canvas.addEventListener("blur", this._onCanvasBlur);
  8239. this._onBlur = function () {
  8240. if (_this.disablePerformanceMonitorInBackground) {
  8241. _this._performanceMonitor.disable();
  8242. }
  8243. _this._windowIsBackground = true;
  8244. };
  8245. this._onFocus = function () {
  8246. if (_this.disablePerformanceMonitorInBackground) {
  8247. _this._performanceMonitor.enable();
  8248. }
  8249. _this._windowIsBackground = false;
  8250. };
  8251. this._onCanvasPointerOut = function () {
  8252. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  8253. };
  8254. window.addEventListener("blur", this._onBlur);
  8255. window.addEventListener("focus", this._onFocus);
  8256. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  8257. // Context lost
  8258. if (!this._doNotHandleContextLost) {
  8259. this._onContextLost = function (evt) {
  8260. evt.preventDefault();
  8261. _this._contextWasLost = true;
  8262. BABYLON.Tools.Warn("WebGL context lost.");
  8263. _this.onContextLostObservable.notifyObservers(_this);
  8264. };
  8265. this._onContextRestored = function (evt) {
  8266. // Adding a timeout to avoid race condition at browser level
  8267. setTimeout(function () {
  8268. // Rebuild gl context
  8269. _this._initGLContext();
  8270. // Rebuild effects
  8271. _this._rebuildEffects();
  8272. // Rebuild textures
  8273. _this._rebuildInternalTextures();
  8274. // Rebuild buffers
  8275. _this._rebuildBuffers();
  8276. // Cache
  8277. _this.wipeCaches(true);
  8278. BABYLON.Tools.Warn("WebGL context successfully restored.");
  8279. _this.onContextRestoredObservable.notifyObservers(_this);
  8280. _this._contextWasLost = false;
  8281. }, 0);
  8282. };
  8283. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  8284. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  8285. }
  8286. }
  8287. else {
  8288. this._gl = canvasOrContext;
  8289. this._renderingCanvas = this._gl.canvas;
  8290. if (this._gl.renderbufferStorageMultisample) {
  8291. this._webGLVersion = 2.0;
  8292. }
  8293. options.stencil = this._gl.getContextAttributes().stencil;
  8294. }
  8295. // Viewport
  8296. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  8297. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  8298. this.resize();
  8299. this._isStencilEnable = options.stencil ? true : false;
  8300. this._initGLContext();
  8301. if (canvas) {
  8302. // Fullscreen
  8303. this._onFullscreenChange = function () {
  8304. if (document.fullscreen !== undefined) {
  8305. _this.isFullscreen = document.fullscreen;
  8306. }
  8307. else if (document.mozFullScreen !== undefined) {
  8308. _this.isFullscreen = document.mozFullScreen;
  8309. }
  8310. else if (document.webkitIsFullScreen !== undefined) {
  8311. _this.isFullscreen = document.webkitIsFullScreen;
  8312. }
  8313. else if (document.msIsFullScreen !== undefined) {
  8314. _this.isFullscreen = document.msIsFullScreen;
  8315. }
  8316. // Pointer lock
  8317. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  8318. canvas.requestPointerLock = canvas.requestPointerLock ||
  8319. canvas.msRequestPointerLock ||
  8320. canvas.mozRequestPointerLock ||
  8321. canvas.webkitRequestPointerLock;
  8322. if (canvas.requestPointerLock) {
  8323. canvas.requestPointerLock();
  8324. }
  8325. }
  8326. };
  8327. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  8328. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  8329. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  8330. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  8331. // Pointer lock
  8332. this._onPointerLockChange = function () {
  8333. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  8334. document.webkitPointerLockElement === canvas ||
  8335. document.msPointerLockElement === canvas ||
  8336. document.pointerLockElement === canvas);
  8337. };
  8338. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  8339. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  8340. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  8341. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  8342. this._onVRDisplayPointerRestricted = function () {
  8343. if (canvas) {
  8344. canvas.requestPointerLock();
  8345. }
  8346. };
  8347. this._onVRDisplayPointerUnrestricted = function () {
  8348. document.exitPointerLock();
  8349. };
  8350. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  8351. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  8352. }
  8353. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  8354. Engine.audioEngine = new BABYLON.AudioEngine();
  8355. }
  8356. // Prepare buffer pointers
  8357. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  8358. this._currentBufferPointers[i] = new BufferPointer();
  8359. }
  8360. // Load WebVR Devices
  8361. if (options.autoEnableWebVR) {
  8362. this.initWebVR();
  8363. }
  8364. // Detect if we are running on a faulty buggy OS.
  8365. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  8366. // Detect if we are running on a faulty buggy desktop OS.
  8367. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  8368. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  8369. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  8370. }
  8371. Object.defineProperty(Engine, "LastCreatedEngine", {
  8372. get: function () {
  8373. if (Engine.Instances.length === 0) {
  8374. return null;
  8375. }
  8376. return Engine.Instances[Engine.Instances.length - 1];
  8377. },
  8378. enumerable: true,
  8379. configurable: true
  8380. });
  8381. Object.defineProperty(Engine, "LastCreatedScene", {
  8382. get: function () {
  8383. var lastCreatedEngine = Engine.LastCreatedEngine;
  8384. if (!lastCreatedEngine) {
  8385. return null;
  8386. }
  8387. if (lastCreatedEngine.scenes.length === 0) {
  8388. return null;
  8389. }
  8390. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  8391. },
  8392. enumerable: true,
  8393. configurable: true
  8394. });
  8395. /**
  8396. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  8397. */
  8398. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  8399. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  8400. var engine = Engine.Instances[engineIndex];
  8401. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  8402. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  8403. }
  8404. }
  8405. };
  8406. Object.defineProperty(Engine, "NEVER", {
  8407. get: function () {
  8408. return Engine._NEVER;
  8409. },
  8410. enumerable: true,
  8411. configurable: true
  8412. });
  8413. Object.defineProperty(Engine, "ALWAYS", {
  8414. get: function () {
  8415. return Engine._ALWAYS;
  8416. },
  8417. enumerable: true,
  8418. configurable: true
  8419. });
  8420. Object.defineProperty(Engine, "LESS", {
  8421. get: function () {
  8422. return Engine._LESS;
  8423. },
  8424. enumerable: true,
  8425. configurable: true
  8426. });
  8427. Object.defineProperty(Engine, "EQUAL", {
  8428. get: function () {
  8429. return Engine._EQUAL;
  8430. },
  8431. enumerable: true,
  8432. configurable: true
  8433. });
  8434. Object.defineProperty(Engine, "LEQUAL", {
  8435. get: function () {
  8436. return Engine._LEQUAL;
  8437. },
  8438. enumerable: true,
  8439. configurable: true
  8440. });
  8441. Object.defineProperty(Engine, "GREATER", {
  8442. get: function () {
  8443. return Engine._GREATER;
  8444. },
  8445. enumerable: true,
  8446. configurable: true
  8447. });
  8448. Object.defineProperty(Engine, "GEQUAL", {
  8449. get: function () {
  8450. return Engine._GEQUAL;
  8451. },
  8452. enumerable: true,
  8453. configurable: true
  8454. });
  8455. Object.defineProperty(Engine, "NOTEQUAL", {
  8456. get: function () {
  8457. return Engine._NOTEQUAL;
  8458. },
  8459. enumerable: true,
  8460. configurable: true
  8461. });
  8462. Object.defineProperty(Engine, "KEEP", {
  8463. get: function () {
  8464. return Engine._KEEP;
  8465. },
  8466. enumerable: true,
  8467. configurable: true
  8468. });
  8469. Object.defineProperty(Engine, "REPLACE", {
  8470. get: function () {
  8471. return Engine._REPLACE;
  8472. },
  8473. enumerable: true,
  8474. configurable: true
  8475. });
  8476. Object.defineProperty(Engine, "INCR", {
  8477. get: function () {
  8478. return Engine._INCR;
  8479. },
  8480. enumerable: true,
  8481. configurable: true
  8482. });
  8483. Object.defineProperty(Engine, "DECR", {
  8484. get: function () {
  8485. return Engine._DECR;
  8486. },
  8487. enumerable: true,
  8488. configurable: true
  8489. });
  8490. Object.defineProperty(Engine, "INVERT", {
  8491. get: function () {
  8492. return Engine._INVERT;
  8493. },
  8494. enumerable: true,
  8495. configurable: true
  8496. });
  8497. Object.defineProperty(Engine, "INCR_WRAP", {
  8498. get: function () {
  8499. return Engine._INCR_WRAP;
  8500. },
  8501. enumerable: true,
  8502. configurable: true
  8503. });
  8504. Object.defineProperty(Engine, "DECR_WRAP", {
  8505. get: function () {
  8506. return Engine._DECR_WRAP;
  8507. },
  8508. enumerable: true,
  8509. configurable: true
  8510. });
  8511. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  8512. get: function () {
  8513. return Engine._ALPHA_DISABLE;
  8514. },
  8515. enumerable: true,
  8516. configurable: true
  8517. });
  8518. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  8519. get: function () {
  8520. return Engine._ALPHA_ONEONE;
  8521. },
  8522. enumerable: true,
  8523. configurable: true
  8524. });
  8525. Object.defineProperty(Engine, "ALPHA_ADD", {
  8526. get: function () {
  8527. return Engine._ALPHA_ADD;
  8528. },
  8529. enumerable: true,
  8530. configurable: true
  8531. });
  8532. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  8533. get: function () {
  8534. return Engine._ALPHA_COMBINE;
  8535. },
  8536. enumerable: true,
  8537. configurable: true
  8538. });
  8539. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  8540. get: function () {
  8541. return Engine._ALPHA_SUBTRACT;
  8542. },
  8543. enumerable: true,
  8544. configurable: true
  8545. });
  8546. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  8547. get: function () {
  8548. return Engine._ALPHA_MULTIPLY;
  8549. },
  8550. enumerable: true,
  8551. configurable: true
  8552. });
  8553. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  8554. get: function () {
  8555. return Engine._ALPHA_MAXIMIZED;
  8556. },
  8557. enumerable: true,
  8558. configurable: true
  8559. });
  8560. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  8561. get: function () {
  8562. return Engine._ALPHA_PREMULTIPLIED;
  8563. },
  8564. enumerable: true,
  8565. configurable: true
  8566. });
  8567. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  8568. get: function () {
  8569. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  8570. },
  8571. enumerable: true,
  8572. configurable: true
  8573. });
  8574. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  8575. get: function () {
  8576. return Engine._ALPHA_INTERPOLATE;
  8577. },
  8578. enumerable: true,
  8579. configurable: true
  8580. });
  8581. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  8582. get: function () {
  8583. return Engine._ALPHA_SCREENMODE;
  8584. },
  8585. enumerable: true,
  8586. configurable: true
  8587. });
  8588. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  8589. get: function () {
  8590. return Engine._DELAYLOADSTATE_NONE;
  8591. },
  8592. enumerable: true,
  8593. configurable: true
  8594. });
  8595. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  8596. get: function () {
  8597. return Engine._DELAYLOADSTATE_LOADED;
  8598. },
  8599. enumerable: true,
  8600. configurable: true
  8601. });
  8602. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  8603. get: function () {
  8604. return Engine._DELAYLOADSTATE_LOADING;
  8605. },
  8606. enumerable: true,
  8607. configurable: true
  8608. });
  8609. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  8610. get: function () {
  8611. return Engine._DELAYLOADSTATE_NOTLOADED;
  8612. },
  8613. enumerable: true,
  8614. configurable: true
  8615. });
  8616. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  8617. get: function () {
  8618. return Engine._TEXTUREFORMAT_ALPHA;
  8619. },
  8620. enumerable: true,
  8621. configurable: true
  8622. });
  8623. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  8624. get: function () {
  8625. return Engine._TEXTUREFORMAT_LUMINANCE;
  8626. },
  8627. enumerable: true,
  8628. configurable: true
  8629. });
  8630. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8631. get: function () {
  8632. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8633. },
  8634. enumerable: true,
  8635. configurable: true
  8636. });
  8637. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8638. get: function () {
  8639. return Engine._TEXTUREFORMAT_RGB;
  8640. },
  8641. enumerable: true,
  8642. configurable: true
  8643. });
  8644. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8645. get: function () {
  8646. return Engine._TEXTUREFORMAT_RGBA;
  8647. },
  8648. enumerable: true,
  8649. configurable: true
  8650. });
  8651. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8652. get: function () {
  8653. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8654. },
  8655. enumerable: true,
  8656. configurable: true
  8657. });
  8658. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8659. get: function () {
  8660. return Engine._TEXTURETYPE_FLOAT;
  8661. },
  8662. enumerable: true,
  8663. configurable: true
  8664. });
  8665. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8666. get: function () {
  8667. return Engine._TEXTURETYPE_HALF_FLOAT;
  8668. },
  8669. enumerable: true,
  8670. configurable: true
  8671. });
  8672. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  8673. get: function () {
  8674. return Engine._SCALEMODE_FLOOR;
  8675. },
  8676. enumerable: true,
  8677. configurable: true
  8678. });
  8679. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  8680. get: function () {
  8681. return Engine._SCALEMODE_NEAREST;
  8682. },
  8683. enumerable: true,
  8684. configurable: true
  8685. });
  8686. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  8687. get: function () {
  8688. return Engine._SCALEMODE_CEILING;
  8689. },
  8690. enumerable: true,
  8691. configurable: true
  8692. });
  8693. Object.defineProperty(Engine, "Version", {
  8694. get: function () {
  8695. return "3.2.0-alpha2";
  8696. },
  8697. enumerable: true,
  8698. configurable: true
  8699. });
  8700. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  8701. get: function () {
  8702. return this._vrExclusivePointerMode;
  8703. },
  8704. enumerable: true,
  8705. configurable: true
  8706. });
  8707. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  8708. get: function () {
  8709. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  8710. },
  8711. enumerable: true,
  8712. configurable: true
  8713. });
  8714. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  8715. get: function () {
  8716. return this._webGLVersion < 2 || this.forcePOTTextures;
  8717. },
  8718. enumerable: true,
  8719. configurable: true
  8720. });
  8721. Object.defineProperty(Engine.prototype, "badOS", {
  8722. get: function () {
  8723. return this._badOS;
  8724. },
  8725. enumerable: true,
  8726. configurable: true
  8727. });
  8728. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  8729. get: function () {
  8730. return this._badDesktopOS;
  8731. },
  8732. enumerable: true,
  8733. configurable: true
  8734. });
  8735. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  8736. get: function () {
  8737. return this._performanceMonitor;
  8738. },
  8739. enumerable: true,
  8740. configurable: true
  8741. });
  8742. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8743. get: function () {
  8744. return this._texturesSupported;
  8745. },
  8746. enumerable: true,
  8747. configurable: true
  8748. });
  8749. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8750. get: function () {
  8751. return this._textureFormatInUse;
  8752. },
  8753. enumerable: true,
  8754. configurable: true
  8755. });
  8756. Object.defineProperty(Engine.prototype, "currentViewport", {
  8757. get: function () {
  8758. return this._cachedViewport;
  8759. },
  8760. enumerable: true,
  8761. configurable: true
  8762. });
  8763. Object.defineProperty(Engine.prototype, "emptyTexture", {
  8764. // Empty texture
  8765. get: function () {
  8766. if (!this._emptyTexture) {
  8767. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8768. }
  8769. return this._emptyTexture;
  8770. },
  8771. enumerable: true,
  8772. configurable: true
  8773. });
  8774. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  8775. get: function () {
  8776. if (!this._emptyTexture3D) {
  8777. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8778. }
  8779. return this._emptyTexture3D;
  8780. },
  8781. enumerable: true,
  8782. configurable: true
  8783. });
  8784. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  8785. get: function () {
  8786. if (!this._emptyCubeTexture) {
  8787. var faceData = new Uint8Array(4);
  8788. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  8789. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8790. }
  8791. return this._emptyCubeTexture;
  8792. },
  8793. enumerable: true,
  8794. configurable: true
  8795. });
  8796. Engine.prototype._rebuildInternalTextures = function () {
  8797. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  8798. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  8799. var internalTexture = currentState_1[_i];
  8800. internalTexture._rebuild();
  8801. }
  8802. };
  8803. Engine.prototype._rebuildEffects = function () {
  8804. for (var key in this._compiledEffects) {
  8805. var effect = this._compiledEffects[key];
  8806. effect._prepareEffect();
  8807. }
  8808. BABYLON.Effect.ResetCache();
  8809. };
  8810. Engine.prototype._rebuildBuffers = function () {
  8811. // Index / Vertex
  8812. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  8813. var scene = _a[_i];
  8814. scene.resetCachedMaterial();
  8815. scene._rebuildGeometries();
  8816. scene._rebuildTextures();
  8817. }
  8818. // Uniforms
  8819. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  8820. var uniformBuffer = _c[_b];
  8821. uniformBuffer._rebuild();
  8822. }
  8823. };
  8824. Engine.prototype._initGLContext = function () {
  8825. // Caps
  8826. this._caps = new EngineCapabilities();
  8827. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8828. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  8829. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  8830. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8831. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8832. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8833. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8834. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8835. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8836. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8837. // Infos
  8838. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8839. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8840. if (rendererInfo != null) {
  8841. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8842. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8843. }
  8844. if (!this._glVendor) {
  8845. this._glVendor = "Unknown vendor";
  8846. }
  8847. if (!this._glRenderer) {
  8848. this._glRenderer = "Unknown renderer";
  8849. }
  8850. // Constants
  8851. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  8852. if (this._gl.RGBA16F !== 0x881A) {
  8853. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  8854. }
  8855. if (this._gl.RGBA32F !== 0x8814) {
  8856. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  8857. }
  8858. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  8859. this._gl.DEPTH24_STENCIL8 = 35056;
  8860. }
  8861. // Extensions
  8862. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8863. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8864. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8865. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8866. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8867. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8868. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8869. 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');
  8870. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8871. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8872. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8873. this._caps.highPrecisionShaderSupported = true;
  8874. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  8875. if (this._caps.timerQuery) {
  8876. if (this._webGLVersion === 1) {
  8877. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  8878. }
  8879. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  8880. }
  8881. // Checks if some of the format renders first to allow the use of webgl inspector.
  8882. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8883. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8884. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8885. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8886. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8887. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8888. if (this._webGLVersion > 1) {
  8889. this._gl.HALF_FLOAT_OES = 0x140B;
  8890. }
  8891. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8892. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8893. // Draw buffers
  8894. if (this._webGLVersion > 1) {
  8895. this._caps.drawBuffersExtension = true;
  8896. }
  8897. else {
  8898. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  8899. if (drawBuffersExtension !== null) {
  8900. this._caps.drawBuffersExtension = true;
  8901. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  8902. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  8903. for (var i = 0; i < 16; i++) {
  8904. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  8905. }
  8906. }
  8907. else {
  8908. this._caps.drawBuffersExtension = false;
  8909. }
  8910. }
  8911. // Depth Texture
  8912. if (this._webGLVersion > 1) {
  8913. this._caps.depthTextureExtension = true;
  8914. }
  8915. else {
  8916. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  8917. if (depthTextureExtension != null) {
  8918. this._caps.depthTextureExtension = true;
  8919. }
  8920. }
  8921. // Vertex array object
  8922. if (this._webGLVersion > 1) {
  8923. this._caps.vertexArrayObject = true;
  8924. }
  8925. else {
  8926. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8927. if (vertexArrayObjectExtension != null) {
  8928. this._caps.vertexArrayObject = true;
  8929. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8930. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8931. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8932. }
  8933. else {
  8934. this._caps.vertexArrayObject = false;
  8935. }
  8936. }
  8937. // Instances count
  8938. if (this._webGLVersion > 1) {
  8939. this._caps.instancedArrays = true;
  8940. }
  8941. else {
  8942. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8943. if (instanceExtension != null) {
  8944. this._caps.instancedArrays = true;
  8945. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8946. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8947. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8948. }
  8949. else {
  8950. this._caps.instancedArrays = false;
  8951. }
  8952. }
  8953. // Intelligently add supported compressed formats in order to check for.
  8954. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8955. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8956. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8957. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8958. if (this._caps.astc)
  8959. this.texturesSupported.push('-astc.ktx');
  8960. if (this._caps.s3tc)
  8961. this.texturesSupported.push('-dxt.ktx');
  8962. if (this._caps.pvrtc)
  8963. this.texturesSupported.push('-pvrtc.ktx');
  8964. if (this._caps.etc2)
  8965. this.texturesSupported.push('-etc2.ktx');
  8966. if (this._caps.etc1)
  8967. this.texturesSupported.push('-etc1.ktx');
  8968. if (this._gl.getShaderPrecisionFormat) {
  8969. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8970. if (highp) {
  8971. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8972. }
  8973. }
  8974. // Depth buffer
  8975. this.setDepthBuffer(true);
  8976. this.setDepthFunctionToLessOrEqual();
  8977. this.setDepthWrite(true);
  8978. // Texture maps
  8979. for (var slot = 0; slot < this._caps.maxCombinedTexturesImageUnits; slot++) {
  8980. this._nextFreeTextureSlots.push(slot);
  8981. }
  8982. };
  8983. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8984. get: function () {
  8985. return this._webGLVersion;
  8986. },
  8987. enumerable: true,
  8988. configurable: true
  8989. });
  8990. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8991. /**
  8992. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8993. */
  8994. get: function () {
  8995. return this._isStencilEnable;
  8996. },
  8997. enumerable: true,
  8998. configurable: true
  8999. });
  9000. Engine.prototype._prepareWorkingCanvas = function () {
  9001. if (this._workingCanvas) {
  9002. return;
  9003. }
  9004. this._workingCanvas = document.createElement("canvas");
  9005. var context = this._workingCanvas.getContext("2d");
  9006. if (context) {
  9007. this._workingContext = context;
  9008. }
  9009. };
  9010. Engine.prototype.resetTextureCache = function () {
  9011. for (var key in this._boundTexturesCache) {
  9012. var boundTexture = this._boundTexturesCache[key];
  9013. if (boundTexture) {
  9014. this._removeDesignatedSlot(boundTexture);
  9015. }
  9016. this._boundTexturesCache[key] = null;
  9017. }
  9018. this._nextFreeTextureSlots = [];
  9019. for (var slot = 0; slot < this._caps.maxCombinedTexturesImageUnits; slot++) {
  9020. this._nextFreeTextureSlots.push(slot);
  9021. }
  9022. this._activeChannel = -1;
  9023. };
  9024. Engine.prototype.isDeterministicLockStep = function () {
  9025. return this._deterministicLockstep;
  9026. };
  9027. Engine.prototype.getLockstepMaxSteps = function () {
  9028. return this._lockstepMaxSteps;
  9029. };
  9030. Engine.prototype.getGlInfo = function () {
  9031. return {
  9032. vendor: this._glVendor,
  9033. renderer: this._glRenderer,
  9034. version: this._glVersion
  9035. };
  9036. };
  9037. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  9038. if (useScreen === void 0) { useScreen = false; }
  9039. var viewport = camera.viewport;
  9040. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  9041. };
  9042. Engine.prototype.getRenderWidth = function (useScreen) {
  9043. if (useScreen === void 0) { useScreen = false; }
  9044. if (!useScreen && this._currentRenderTarget) {
  9045. return this._currentRenderTarget.width;
  9046. }
  9047. return this._gl.drawingBufferWidth;
  9048. };
  9049. Engine.prototype.getRenderHeight = function (useScreen) {
  9050. if (useScreen === void 0) { useScreen = false; }
  9051. if (!useScreen && this._currentRenderTarget) {
  9052. return this._currentRenderTarget.height;
  9053. }
  9054. return this._gl.drawingBufferHeight;
  9055. };
  9056. Engine.prototype.getRenderingCanvas = function () {
  9057. return this._renderingCanvas;
  9058. };
  9059. Engine.prototype.getRenderingCanvasClientRect = function () {
  9060. if (!this._renderingCanvas) {
  9061. return null;
  9062. }
  9063. return this._renderingCanvas.getBoundingClientRect();
  9064. };
  9065. Engine.prototype.setHardwareScalingLevel = function (level) {
  9066. this._hardwareScalingLevel = level;
  9067. this.resize();
  9068. };
  9069. Engine.prototype.getHardwareScalingLevel = function () {
  9070. return this._hardwareScalingLevel;
  9071. };
  9072. Engine.prototype.getLoadedTexturesCache = function () {
  9073. return this._internalTexturesCache;
  9074. };
  9075. Engine.prototype.getCaps = function () {
  9076. return this._caps;
  9077. };
  9078. Object.defineProperty(Engine.prototype, "drawCalls", {
  9079. /** The number of draw calls submitted last frame */
  9080. get: function () {
  9081. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  9082. return 0;
  9083. },
  9084. enumerable: true,
  9085. configurable: true
  9086. });
  9087. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  9088. get: function () {
  9089. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  9090. return null;
  9091. },
  9092. enumerable: true,
  9093. configurable: true
  9094. });
  9095. Engine.prototype.getDepthFunction = function () {
  9096. return this._depthCullingState.depthFunc;
  9097. };
  9098. Engine.prototype.setDepthFunction = function (depthFunc) {
  9099. this._depthCullingState.depthFunc = depthFunc;
  9100. };
  9101. Engine.prototype.setDepthFunctionToGreater = function () {
  9102. this._depthCullingState.depthFunc = this._gl.GREATER;
  9103. };
  9104. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  9105. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  9106. };
  9107. Engine.prototype.setDepthFunctionToLess = function () {
  9108. this._depthCullingState.depthFunc = this._gl.LESS;
  9109. };
  9110. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  9111. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  9112. };
  9113. Engine.prototype.getStencilBuffer = function () {
  9114. return this._stencilState.stencilTest;
  9115. };
  9116. Engine.prototype.setStencilBuffer = function (enable) {
  9117. this._stencilState.stencilTest = enable;
  9118. };
  9119. Engine.prototype.getStencilMask = function () {
  9120. return this._stencilState.stencilMask;
  9121. };
  9122. Engine.prototype.setStencilMask = function (mask) {
  9123. this._stencilState.stencilMask = mask;
  9124. };
  9125. Engine.prototype.getStencilFunction = function () {
  9126. return this._stencilState.stencilFunc;
  9127. };
  9128. Engine.prototype.getStencilFunctionReference = function () {
  9129. return this._stencilState.stencilFuncRef;
  9130. };
  9131. Engine.prototype.getStencilFunctionMask = function () {
  9132. return this._stencilState.stencilFuncMask;
  9133. };
  9134. Engine.prototype.setStencilFunction = function (stencilFunc) {
  9135. this._stencilState.stencilFunc = stencilFunc;
  9136. };
  9137. Engine.prototype.setStencilFunctionReference = function (reference) {
  9138. this._stencilState.stencilFuncRef = reference;
  9139. };
  9140. Engine.prototype.setStencilFunctionMask = function (mask) {
  9141. this._stencilState.stencilFuncMask = mask;
  9142. };
  9143. Engine.prototype.getStencilOperationFail = function () {
  9144. return this._stencilState.stencilOpStencilFail;
  9145. };
  9146. Engine.prototype.getStencilOperationDepthFail = function () {
  9147. return this._stencilState.stencilOpDepthFail;
  9148. };
  9149. Engine.prototype.getStencilOperationPass = function () {
  9150. return this._stencilState.stencilOpStencilDepthPass;
  9151. };
  9152. Engine.prototype.setStencilOperationFail = function (operation) {
  9153. this._stencilState.stencilOpStencilFail = operation;
  9154. };
  9155. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  9156. this._stencilState.stencilOpDepthFail = operation;
  9157. };
  9158. Engine.prototype.setStencilOperationPass = function (operation) {
  9159. this._stencilState.stencilOpStencilDepthPass = operation;
  9160. };
  9161. Engine.prototype.setDitheringState = function (value) {
  9162. if (value) {
  9163. this._gl.enable(this._gl.DITHER);
  9164. }
  9165. else {
  9166. this._gl.disable(this._gl.DITHER);
  9167. }
  9168. };
  9169. Engine.prototype.setRasterizerState = function (value) {
  9170. if (value) {
  9171. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  9172. }
  9173. else {
  9174. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  9175. }
  9176. };
  9177. /**
  9178. * stop executing a render loop function and remove it from the execution array
  9179. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  9180. */
  9181. Engine.prototype.stopRenderLoop = function (renderFunction) {
  9182. if (!renderFunction) {
  9183. this._activeRenderLoops = [];
  9184. return;
  9185. }
  9186. var index = this._activeRenderLoops.indexOf(renderFunction);
  9187. if (index >= 0) {
  9188. this._activeRenderLoops.splice(index, 1);
  9189. }
  9190. };
  9191. Engine.prototype._renderLoop = function () {
  9192. if (!this._contextWasLost) {
  9193. var shouldRender = true;
  9194. if (!this.renderEvenInBackground && this._windowIsBackground) {
  9195. shouldRender = false;
  9196. }
  9197. if (shouldRender) {
  9198. // Start new frame
  9199. this.beginFrame();
  9200. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  9201. var renderFunction = this._activeRenderLoops[index];
  9202. renderFunction();
  9203. }
  9204. // Present
  9205. this.endFrame();
  9206. }
  9207. }
  9208. if (this._activeRenderLoops.length > 0) {
  9209. // Register new frame
  9210. var requester = null;
  9211. if (this._vrDisplay && this._vrDisplay.isPresenting)
  9212. requester = this._vrDisplay;
  9213. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  9214. }
  9215. else {
  9216. this._renderingQueueLaunched = false;
  9217. }
  9218. };
  9219. /**
  9220. * Register and execute a render loop. The engine can have more than one render function.
  9221. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  9222. * @example
  9223. * engine.runRenderLoop(function () {
  9224. * scene.render()
  9225. * })
  9226. */
  9227. Engine.prototype.runRenderLoop = function (renderFunction) {
  9228. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  9229. return;
  9230. }
  9231. this._activeRenderLoops.push(renderFunction);
  9232. if (!this._renderingQueueLaunched) {
  9233. this._renderingQueueLaunched = true;
  9234. this._bindedRenderFunction = this._renderLoop.bind(this);
  9235. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  9236. }
  9237. };
  9238. /**
  9239. * Toggle full screen mode.
  9240. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  9241. * @param {any} options - an options object to be sent to the requestFullscreen function
  9242. */
  9243. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  9244. if (this.isFullscreen) {
  9245. BABYLON.Tools.ExitFullscreen();
  9246. }
  9247. else {
  9248. this._pointerLockRequested = requestPointerLock;
  9249. if (this._renderingCanvas) {
  9250. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  9251. }
  9252. }
  9253. };
  9254. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  9255. if (stencil === void 0) { stencil = false; }
  9256. this.applyStates();
  9257. var mode = 0;
  9258. if (backBuffer && color) {
  9259. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  9260. mode |= this._gl.COLOR_BUFFER_BIT;
  9261. }
  9262. if (depth) {
  9263. this._gl.clearDepth(1.0);
  9264. mode |= this._gl.DEPTH_BUFFER_BIT;
  9265. }
  9266. if (stencil) {
  9267. this._gl.clearStencil(0);
  9268. mode |= this._gl.STENCIL_BUFFER_BIT;
  9269. }
  9270. this._gl.clear(mode);
  9271. };
  9272. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  9273. var gl = this._gl;
  9274. // Save state
  9275. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  9276. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  9277. // Change state
  9278. gl.enable(gl.SCISSOR_TEST);
  9279. gl.scissor(x, y, width, height);
  9280. // Clear
  9281. this.clear(clearColor, true, true, true);
  9282. // Restore state
  9283. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  9284. if (curScissor === true) {
  9285. gl.enable(gl.SCISSOR_TEST);
  9286. }
  9287. else {
  9288. gl.disable(gl.SCISSOR_TEST);
  9289. }
  9290. };
  9291. /**
  9292. * Set the WebGL's viewport
  9293. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  9294. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  9295. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  9296. */
  9297. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  9298. var width = requiredWidth || this.getRenderWidth();
  9299. var height = requiredHeight || this.getRenderHeight();
  9300. var x = viewport.x || 0;
  9301. var y = viewport.y || 0;
  9302. this._cachedViewport = viewport;
  9303. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  9304. };
  9305. /**
  9306. * Directly set the WebGL Viewport
  9307. * The x, y, width & height are directly passed to the WebGL call
  9308. * @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.
  9309. */
  9310. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  9311. var currentViewport = this._cachedViewport;
  9312. this._cachedViewport = null;
  9313. this._gl.viewport(x, y, width, height);
  9314. return currentViewport;
  9315. };
  9316. Engine.prototype.beginFrame = function () {
  9317. this.onBeginFrameObservable.notifyObservers(this);
  9318. this._measureFps();
  9319. };
  9320. Engine.prototype.endFrame = function () {
  9321. //force a flush in case we are using a bad OS.
  9322. if (this._badOS) {
  9323. this.flushFramebuffer();
  9324. }
  9325. //submit frame to the vr device, if enabled
  9326. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9327. // TODO: We should only submit the frame if we read frameData successfully.
  9328. this._vrDisplay.submitFrame();
  9329. }
  9330. this.onEndFrameObservable.notifyObservers(this);
  9331. };
  9332. /**
  9333. * resize the view according to the canvas' size.
  9334. * @example
  9335. * window.addEventListener("resize", function () {
  9336. * engine.resize();
  9337. * });
  9338. */
  9339. Engine.prototype.resize = function () {
  9340. // We're not resizing the size of the canvas while in VR mode & presenting
  9341. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  9342. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  9343. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  9344. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  9345. }
  9346. };
  9347. /**
  9348. * force a specific size of the canvas
  9349. * @param {number} width - the new canvas' width
  9350. * @param {number} height - the new canvas' height
  9351. */
  9352. Engine.prototype.setSize = function (width, height) {
  9353. if (!this._renderingCanvas) {
  9354. return;
  9355. }
  9356. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  9357. return;
  9358. }
  9359. this._renderingCanvas.width = width;
  9360. this._renderingCanvas.height = height;
  9361. for (var index = 0; index < this.scenes.length; index++) {
  9362. var scene = this.scenes[index];
  9363. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  9364. var cam = scene.cameras[camIndex];
  9365. cam._currentRenderId = 0;
  9366. }
  9367. }
  9368. if (this.onResizeObservable.hasObservers) {
  9369. this.onResizeObservable.notifyObservers(this);
  9370. }
  9371. };
  9372. // WebVR functions
  9373. Engine.prototype.isVRDevicePresent = function () {
  9374. return !!this._vrDisplay;
  9375. };
  9376. Engine.prototype.getVRDevice = function () {
  9377. return this._vrDisplay;
  9378. };
  9379. Engine.prototype.initWebVR = function () {
  9380. var _this = this;
  9381. var notifyObservers = function () {
  9382. var eventArgs = {
  9383. vrDisplay: _this._vrDisplay,
  9384. vrSupported: _this._vrSupported
  9385. };
  9386. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  9387. };
  9388. if (!this._onVrDisplayConnect) {
  9389. this._onVrDisplayConnect = function (event) {
  9390. _this._vrDisplay = event.display;
  9391. notifyObservers();
  9392. };
  9393. this._onVrDisplayDisconnect = function () {
  9394. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  9395. _this._vrDisplay = undefined;
  9396. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  9397. notifyObservers();
  9398. };
  9399. this._onVrDisplayPresentChange = function () {
  9400. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  9401. };
  9402. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  9403. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  9404. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  9405. }
  9406. this._getVRDisplays(notifyObservers);
  9407. return this.onVRDisplayChangedObservable;
  9408. };
  9409. Engine.prototype.enableVR = function () {
  9410. var _this = this;
  9411. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  9412. var onResolved = function () {
  9413. _this.onVRRequestPresentComplete.notifyObservers(true);
  9414. _this._onVRFullScreenTriggered();
  9415. };
  9416. var onRejected = function () {
  9417. _this.onVRRequestPresentComplete.notifyObservers(false);
  9418. };
  9419. this.onVRRequestPresentStart.notifyObservers(this);
  9420. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  9421. }
  9422. };
  9423. Engine.prototype.disableVR = function () {
  9424. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9425. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  9426. }
  9427. };
  9428. Engine.prototype._getVRDisplays = function (callback) {
  9429. var _this = this;
  9430. var getWebVRDevices = function (devices) {
  9431. _this._vrSupported = true;
  9432. // note that devices may actually be an empty array. This is fine;
  9433. // we expect this._vrDisplay to be undefined in this case.
  9434. return _this._vrDisplay = devices[0];
  9435. };
  9436. if (navigator.getVRDisplays) {
  9437. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  9438. // TODO: System CANNOT support WebVR, despite API presence.
  9439. _this._vrSupported = false;
  9440. callback();
  9441. });
  9442. }
  9443. else {
  9444. // TODO: Browser does not support WebVR
  9445. this._vrDisplay = undefined;
  9446. this._vrSupported = false;
  9447. callback();
  9448. }
  9449. };
  9450. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  9451. if (this._currentRenderTarget) {
  9452. this.unBindFramebuffer(this._currentRenderTarget);
  9453. }
  9454. this._currentRenderTarget = texture;
  9455. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  9456. var gl = this._gl;
  9457. if (texture.isCube) {
  9458. if (faceIndex === undefined) {
  9459. faceIndex = 0;
  9460. }
  9461. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  9462. }
  9463. if (this._cachedViewport && !forceFullscreenViewport) {
  9464. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  9465. }
  9466. else {
  9467. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  9468. }
  9469. this.wipeCaches();
  9470. };
  9471. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  9472. if (this._currentFramebuffer !== framebuffer) {
  9473. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  9474. this._currentFramebuffer = framebuffer;
  9475. }
  9476. };
  9477. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  9478. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  9479. this._currentRenderTarget = null;
  9480. // If MSAA, we need to bitblt back to main texture
  9481. var gl = this._gl;
  9482. if (texture._MSAAFramebuffer) {
  9483. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  9484. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  9485. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  9486. }
  9487. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  9488. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  9489. gl.generateMipmap(gl.TEXTURE_2D);
  9490. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9491. }
  9492. if (onBeforeUnbind) {
  9493. if (texture._MSAAFramebuffer) {
  9494. // Bind the correct framebuffer
  9495. this.bindUnboundFramebuffer(texture._framebuffer);
  9496. }
  9497. onBeforeUnbind();
  9498. }
  9499. this.bindUnboundFramebuffer(null);
  9500. };
  9501. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  9502. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  9503. this._currentRenderTarget = null;
  9504. // If MSAA, we need to bitblt back to main texture
  9505. var gl = this._gl;
  9506. if (textures[0]._MSAAFramebuffer) {
  9507. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  9508. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  9509. var attachments = textures[0]._attachments;
  9510. if (!attachments) {
  9511. attachments = new Array(textures.length);
  9512. textures[0]._attachments = attachments;
  9513. }
  9514. for (var i = 0; i < textures.length; i++) {
  9515. var texture = textures[i];
  9516. for (var j = 0; j < attachments.length; j++) {
  9517. attachments[j] = gl.NONE;
  9518. }
  9519. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  9520. gl.readBuffer(attachments[i]);
  9521. gl.drawBuffers(attachments);
  9522. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  9523. }
  9524. for (var i = 0; i < attachments.length; i++) {
  9525. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  9526. }
  9527. gl.drawBuffers(attachments);
  9528. }
  9529. for (var i = 0; i < textures.length; i++) {
  9530. var texture = textures[i];
  9531. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  9532. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9533. gl.generateMipmap(gl.TEXTURE_2D);
  9534. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9535. }
  9536. }
  9537. if (onBeforeUnbind) {
  9538. if (textures[0]._MSAAFramebuffer) {
  9539. // Bind the correct framebuffer
  9540. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  9541. }
  9542. onBeforeUnbind();
  9543. }
  9544. this.bindUnboundFramebuffer(null);
  9545. };
  9546. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  9547. if (texture.generateMipMaps) {
  9548. var gl = this._gl;
  9549. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  9550. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9551. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9552. }
  9553. };
  9554. Engine.prototype.flushFramebuffer = function () {
  9555. this._gl.flush();
  9556. };
  9557. Engine.prototype.restoreDefaultFramebuffer = function () {
  9558. if (this._currentRenderTarget) {
  9559. this.unBindFramebuffer(this._currentRenderTarget);
  9560. }
  9561. else {
  9562. this.bindUnboundFramebuffer(null);
  9563. }
  9564. if (this._cachedViewport) {
  9565. this.setViewport(this._cachedViewport);
  9566. }
  9567. this.wipeCaches();
  9568. };
  9569. // UBOs
  9570. Engine.prototype.createUniformBuffer = function (elements) {
  9571. var ubo = this._gl.createBuffer();
  9572. if (!ubo) {
  9573. throw new Error("Unable to create uniform buffer");
  9574. }
  9575. this.bindUniformBuffer(ubo);
  9576. if (elements instanceof Float32Array) {
  9577. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  9578. }
  9579. else {
  9580. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  9581. }
  9582. this.bindUniformBuffer(null);
  9583. ubo.references = 1;
  9584. return ubo;
  9585. };
  9586. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  9587. var ubo = this._gl.createBuffer();
  9588. if (!ubo) {
  9589. throw new Error("Unable to create dynamic uniform buffer");
  9590. }
  9591. this.bindUniformBuffer(ubo);
  9592. if (elements instanceof Float32Array) {
  9593. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  9594. }
  9595. else {
  9596. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  9597. }
  9598. this.bindUniformBuffer(null);
  9599. ubo.references = 1;
  9600. return ubo;
  9601. };
  9602. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  9603. this.bindUniformBuffer(uniformBuffer);
  9604. if (offset === undefined) {
  9605. offset = 0;
  9606. }
  9607. if (count === undefined) {
  9608. if (elements instanceof Float32Array) {
  9609. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  9610. }
  9611. else {
  9612. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  9613. }
  9614. }
  9615. else {
  9616. if (elements instanceof Float32Array) {
  9617. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  9618. }
  9619. else {
  9620. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  9621. }
  9622. }
  9623. this.bindUniformBuffer(null);
  9624. };
  9625. // VBOs
  9626. Engine.prototype._resetVertexBufferBinding = function () {
  9627. this.bindArrayBuffer(null);
  9628. this._cachedVertexBuffers = null;
  9629. };
  9630. Engine.prototype.createVertexBuffer = function (vertices) {
  9631. var vbo = this._gl.createBuffer();
  9632. if (!vbo) {
  9633. throw new Error("Unable to create vertex buffer");
  9634. }
  9635. this.bindArrayBuffer(vbo);
  9636. if (vertices instanceof Float32Array) {
  9637. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  9638. }
  9639. else {
  9640. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  9641. }
  9642. this._resetVertexBufferBinding();
  9643. vbo.references = 1;
  9644. return vbo;
  9645. };
  9646. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  9647. var vbo = this._gl.createBuffer();
  9648. if (!vbo) {
  9649. throw new Error("Unable to create dynamic vertex buffer");
  9650. }
  9651. this.bindArrayBuffer(vbo);
  9652. if (vertices instanceof Float32Array) {
  9653. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  9654. }
  9655. else {
  9656. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  9657. }
  9658. this._resetVertexBufferBinding();
  9659. vbo.references = 1;
  9660. return vbo;
  9661. };
  9662. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  9663. if (offset === void 0) { offset = 0; }
  9664. // Force cache update
  9665. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  9666. this.bindIndexBuffer(indexBuffer);
  9667. var arrayBuffer;
  9668. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  9669. arrayBuffer = indices;
  9670. }
  9671. else {
  9672. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9673. }
  9674. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  9675. this._resetIndexBufferBinding();
  9676. };
  9677. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  9678. this.bindArrayBuffer(vertexBuffer);
  9679. if (offset === undefined) {
  9680. offset = 0;
  9681. }
  9682. if (count === undefined) {
  9683. if (vertices instanceof Float32Array) {
  9684. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  9685. }
  9686. else {
  9687. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  9688. }
  9689. }
  9690. else {
  9691. if (vertices instanceof Float32Array) {
  9692. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  9693. }
  9694. else {
  9695. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  9696. }
  9697. }
  9698. this._resetVertexBufferBinding();
  9699. };
  9700. Engine.prototype._resetIndexBufferBinding = function () {
  9701. this.bindIndexBuffer(null);
  9702. this._cachedIndexBuffer = null;
  9703. };
  9704. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  9705. var vbo = this._gl.createBuffer();
  9706. if (!vbo) {
  9707. throw new Error("Unable to create index buffer");
  9708. }
  9709. this.bindIndexBuffer(vbo);
  9710. // Check for 32 bits indices
  9711. var arrayBuffer;
  9712. var need32Bits = false;
  9713. if (indices instanceof Uint16Array) {
  9714. arrayBuffer = indices;
  9715. }
  9716. else {
  9717. //check 32 bit support
  9718. if (this._caps.uintIndices) {
  9719. if (indices instanceof Uint32Array) {
  9720. arrayBuffer = indices;
  9721. need32Bits = true;
  9722. }
  9723. else {
  9724. //number[] or Int32Array, check if 32 bit is necessary
  9725. for (var index = 0; index < indices.length; index++) {
  9726. if (indices[index] > 65535) {
  9727. need32Bits = true;
  9728. break;
  9729. }
  9730. }
  9731. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9732. }
  9733. }
  9734. else {
  9735. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  9736. arrayBuffer = new Uint16Array(indices);
  9737. }
  9738. }
  9739. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  9740. this._resetIndexBufferBinding();
  9741. vbo.references = 1;
  9742. vbo.is32Bits = need32Bits;
  9743. return vbo;
  9744. };
  9745. Engine.prototype.bindArrayBuffer = function (buffer) {
  9746. if (!this._vaoRecordInProgress) {
  9747. this._unbindVertexArrayObject();
  9748. }
  9749. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  9750. };
  9751. Engine.prototype.bindUniformBuffer = function (buffer) {
  9752. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  9753. };
  9754. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  9755. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  9756. };
  9757. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  9758. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  9759. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  9760. };
  9761. ;
  9762. Engine.prototype.bindIndexBuffer = function (buffer) {
  9763. if (!this._vaoRecordInProgress) {
  9764. this._unbindVertexArrayObject();
  9765. }
  9766. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  9767. };
  9768. Engine.prototype.bindBuffer = function (buffer, target) {
  9769. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  9770. this._gl.bindBuffer(target, buffer);
  9771. this._currentBoundBuffer[target] = buffer;
  9772. }
  9773. };
  9774. Engine.prototype.updateArrayBuffer = function (data) {
  9775. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9776. };
  9777. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  9778. var pointer = this._currentBufferPointers[indx];
  9779. var changed = false;
  9780. if (!pointer.active) {
  9781. changed = true;
  9782. pointer.active = true;
  9783. pointer.index = indx;
  9784. pointer.size = size;
  9785. pointer.type = type;
  9786. pointer.normalized = normalized;
  9787. pointer.stride = stride;
  9788. pointer.offset = offset;
  9789. pointer.buffer = buffer;
  9790. }
  9791. else {
  9792. if (pointer.buffer !== buffer) {
  9793. pointer.buffer = buffer;
  9794. changed = true;
  9795. }
  9796. if (pointer.size !== size) {
  9797. pointer.size = size;
  9798. changed = true;
  9799. }
  9800. if (pointer.type !== type) {
  9801. pointer.type = type;
  9802. changed = true;
  9803. }
  9804. if (pointer.normalized !== normalized) {
  9805. pointer.normalized = normalized;
  9806. changed = true;
  9807. }
  9808. if (pointer.stride !== stride) {
  9809. pointer.stride = stride;
  9810. changed = true;
  9811. }
  9812. if (pointer.offset !== offset) {
  9813. pointer.offset = offset;
  9814. changed = true;
  9815. }
  9816. }
  9817. if (changed || this._vaoRecordInProgress) {
  9818. this.bindArrayBuffer(buffer);
  9819. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  9820. }
  9821. };
  9822. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  9823. if (indexBuffer == null) {
  9824. return;
  9825. }
  9826. if (this._cachedIndexBuffer !== indexBuffer) {
  9827. this._cachedIndexBuffer = indexBuffer;
  9828. this.bindIndexBuffer(indexBuffer);
  9829. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  9830. }
  9831. };
  9832. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  9833. var attributes = effect.getAttributesNames();
  9834. if (!this._vaoRecordInProgress) {
  9835. this._unbindVertexArrayObject();
  9836. }
  9837. this.unbindAllAttributes();
  9838. for (var index = 0; index < attributes.length; index++) {
  9839. var order = effect.getAttributeLocation(index);
  9840. if (order >= 0) {
  9841. var vertexBuffer = vertexBuffers[attributes[index]];
  9842. if (!vertexBuffer) {
  9843. continue;
  9844. }
  9845. this._gl.enableVertexAttribArray(order);
  9846. if (!this._vaoRecordInProgress) {
  9847. this._vertexAttribArraysEnabled[order] = true;
  9848. }
  9849. var buffer = vertexBuffer.getBuffer();
  9850. if (buffer) {
  9851. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  9852. if (vertexBuffer.getIsInstanced()) {
  9853. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  9854. if (!this._vaoRecordInProgress) {
  9855. this._currentInstanceLocations.push(order);
  9856. this._currentInstanceBuffers.push(buffer);
  9857. }
  9858. }
  9859. }
  9860. }
  9861. }
  9862. };
  9863. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  9864. var vao = this._gl.createVertexArray();
  9865. this._vaoRecordInProgress = true;
  9866. this._gl.bindVertexArray(vao);
  9867. this._mustWipeVertexAttributes = true;
  9868. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9869. this.bindIndexBuffer(indexBuffer);
  9870. this._vaoRecordInProgress = false;
  9871. this._gl.bindVertexArray(null);
  9872. return vao;
  9873. };
  9874. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  9875. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  9876. this._cachedVertexArrayObject = vertexArrayObject;
  9877. this._gl.bindVertexArray(vertexArrayObject);
  9878. this._cachedVertexBuffers = null;
  9879. this._cachedIndexBuffer = null;
  9880. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  9881. this._mustWipeVertexAttributes = true;
  9882. }
  9883. };
  9884. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  9885. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  9886. this._cachedVertexBuffers = vertexBuffer;
  9887. this._cachedEffectForVertexBuffers = effect;
  9888. var attributesCount = effect.getAttributesCount();
  9889. this._unbindVertexArrayObject();
  9890. this.unbindAllAttributes();
  9891. var offset = 0;
  9892. for (var index = 0; index < attributesCount; index++) {
  9893. if (index < vertexDeclaration.length) {
  9894. var order = effect.getAttributeLocation(index);
  9895. if (order >= 0) {
  9896. this._gl.enableVertexAttribArray(order);
  9897. this._vertexAttribArraysEnabled[order] = true;
  9898. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9899. }
  9900. offset += vertexDeclaration[index] * 4;
  9901. }
  9902. }
  9903. }
  9904. this._bindIndexBufferWithCache(indexBuffer);
  9905. };
  9906. Engine.prototype._unbindVertexArrayObject = function () {
  9907. if (!this._cachedVertexArrayObject) {
  9908. return;
  9909. }
  9910. this._cachedVertexArrayObject = null;
  9911. this._gl.bindVertexArray(null);
  9912. };
  9913. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9914. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9915. this._cachedVertexBuffers = vertexBuffers;
  9916. this._cachedEffectForVertexBuffers = effect;
  9917. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9918. }
  9919. this._bindIndexBufferWithCache(indexBuffer);
  9920. };
  9921. Engine.prototype.unbindInstanceAttributes = function () {
  9922. var boundBuffer;
  9923. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9924. var instancesBuffer = this._currentInstanceBuffers[i];
  9925. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  9926. boundBuffer = instancesBuffer;
  9927. this.bindArrayBuffer(instancesBuffer);
  9928. }
  9929. var offsetLocation = this._currentInstanceLocations[i];
  9930. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9931. }
  9932. this._currentInstanceBuffers.length = 0;
  9933. this._currentInstanceLocations.length = 0;
  9934. };
  9935. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9936. this._gl.deleteVertexArray(vao);
  9937. };
  9938. Engine.prototype._releaseBuffer = function (buffer) {
  9939. buffer.references--;
  9940. if (buffer.references === 0) {
  9941. this._gl.deleteBuffer(buffer);
  9942. return true;
  9943. }
  9944. return false;
  9945. };
  9946. Engine.prototype.createInstancesBuffer = function (capacity) {
  9947. var buffer = this._gl.createBuffer();
  9948. if (!buffer) {
  9949. throw new Error("Unable to create instance buffer");
  9950. }
  9951. buffer.capacity = capacity;
  9952. this.bindArrayBuffer(buffer);
  9953. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9954. return buffer;
  9955. };
  9956. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9957. this._gl.deleteBuffer(buffer);
  9958. };
  9959. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9960. this.bindArrayBuffer(instancesBuffer);
  9961. if (data) {
  9962. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9963. }
  9964. if (offsetLocations[0].index !== undefined) {
  9965. var stride = 0;
  9966. for (var i = 0; i < offsetLocations.length; i++) {
  9967. var ai = offsetLocations[i];
  9968. stride += ai.attributeSize * 4;
  9969. }
  9970. for (var i = 0; i < offsetLocations.length; i++) {
  9971. var ai = offsetLocations[i];
  9972. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9973. this._gl.enableVertexAttribArray(ai.index);
  9974. this._vertexAttribArraysEnabled[ai.index] = true;
  9975. }
  9976. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9977. this._gl.vertexAttribDivisor(ai.index, 1);
  9978. this._currentInstanceLocations.push(ai.index);
  9979. this._currentInstanceBuffers.push(instancesBuffer);
  9980. }
  9981. }
  9982. else {
  9983. for (var index = 0; index < 4; index++) {
  9984. var offsetLocation = offsetLocations[index];
  9985. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9986. this._gl.enableVertexAttribArray(offsetLocation);
  9987. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9988. }
  9989. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9990. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9991. this._currentInstanceLocations.push(offsetLocation);
  9992. this._currentInstanceBuffers.push(instancesBuffer);
  9993. }
  9994. }
  9995. };
  9996. Engine.prototype.applyStates = function () {
  9997. this._depthCullingState.apply(this._gl);
  9998. this._stencilState.apply(this._gl);
  9999. this._alphaState.apply(this._gl);
  10000. };
  10001. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  10002. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  10003. };
  10004. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  10005. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  10006. };
  10007. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  10008. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  10009. };
  10010. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  10011. // Apply states
  10012. this.applyStates();
  10013. this._drawCalls.addCount(1, false);
  10014. // Render
  10015. var drawMode = this.DrawMode(fillMode);
  10016. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  10017. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  10018. if (instancesCount) {
  10019. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  10020. }
  10021. else {
  10022. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  10023. }
  10024. };
  10025. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  10026. // Apply states
  10027. this.applyStates();
  10028. this._drawCalls.addCount(1, false);
  10029. var drawMode = this.DrawMode(fillMode);
  10030. if (instancesCount) {
  10031. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  10032. }
  10033. else {
  10034. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  10035. }
  10036. };
  10037. Engine.prototype.DrawMode = function (fillMode) {
  10038. switch (fillMode) {
  10039. // Triangle views
  10040. case BABYLON.Material.TriangleFillMode:
  10041. return this._gl.TRIANGLES;
  10042. case BABYLON.Material.PointFillMode:
  10043. return this._gl.POINTS;
  10044. case BABYLON.Material.WireFrameFillMode:
  10045. return this._gl.LINES;
  10046. // Draw modes
  10047. case BABYLON.Material.PointListDrawMode:
  10048. return this._gl.POINTS;
  10049. case BABYLON.Material.LineListDrawMode:
  10050. return this._gl.LINES;
  10051. case BABYLON.Material.LineLoopDrawMode:
  10052. return this._gl.LINE_LOOP;
  10053. case BABYLON.Material.LineStripDrawMode:
  10054. return this._gl.LINE_STRIP;
  10055. case BABYLON.Material.TriangleStripDrawMode:
  10056. return this._gl.TRIANGLE_STRIP;
  10057. case BABYLON.Material.TriangleFanDrawMode:
  10058. return this._gl.TRIANGLE_FAN;
  10059. default:
  10060. return this._gl.TRIANGLES;
  10061. }
  10062. };
  10063. // Shaders
  10064. Engine.prototype._releaseEffect = function (effect) {
  10065. if (this._compiledEffects[effect._key]) {
  10066. delete this._compiledEffects[effect._key];
  10067. this._deleteProgram(effect.getProgram());
  10068. }
  10069. };
  10070. Engine.prototype._deleteProgram = function (program) {
  10071. if (program) {
  10072. program.__SPECTOR_rebuildProgram = null;
  10073. if (program.transformFeedback) {
  10074. this.deleteTransformFeedback(program.transformFeedback);
  10075. program.transformFeedback = null;
  10076. }
  10077. this._gl.deleteProgram(program);
  10078. }
  10079. };
  10080. /**
  10081. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  10082. * @param samplers An array of string used to represent textures
  10083. */
  10084. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  10085. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  10086. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  10087. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  10088. if (this._compiledEffects[name]) {
  10089. var compiledEffect = this._compiledEffects[name];
  10090. if (onCompiled && compiledEffect.isReady()) {
  10091. onCompiled(compiledEffect);
  10092. }
  10093. return compiledEffect;
  10094. }
  10095. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  10096. effect._key = name;
  10097. this._compiledEffects[name] = effect;
  10098. return effect;
  10099. };
  10100. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  10101. if (uniformsNames === void 0) { uniformsNames = []; }
  10102. if (samplers === void 0) { samplers = []; }
  10103. if (defines === void 0) { defines = ""; }
  10104. return this.createEffect({
  10105. vertex: "particles",
  10106. fragmentElement: fragmentName
  10107. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  10108. };
  10109. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  10110. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  10111. context = context || this._gl;
  10112. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  10113. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  10114. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  10115. };
  10116. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  10117. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  10118. context = context || this._gl;
  10119. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  10120. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  10121. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  10122. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  10123. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  10124. this.onAfterShaderCompilationObservable.notifyObservers(this);
  10125. return program;
  10126. };
  10127. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  10128. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  10129. var shaderProgram = context.createProgram();
  10130. if (!shaderProgram) {
  10131. throw new Error("Unable to create program");
  10132. }
  10133. context.attachShader(shaderProgram, vertexShader);
  10134. context.attachShader(shaderProgram, fragmentShader);
  10135. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  10136. var transformFeedback = this.createTransformFeedback();
  10137. this.bindTransformFeedback(transformFeedback);
  10138. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  10139. shaderProgram.transformFeedback = transformFeedback;
  10140. }
  10141. context.linkProgram(shaderProgram);
  10142. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  10143. this.bindTransformFeedback(null);
  10144. }
  10145. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  10146. if (!linked) {
  10147. context.validateProgram(shaderProgram);
  10148. var error = context.getProgramInfoLog(shaderProgram);
  10149. if (error) {
  10150. throw new Error(error);
  10151. }
  10152. }
  10153. context.deleteShader(vertexShader);
  10154. context.deleteShader(fragmentShader);
  10155. return shaderProgram;
  10156. };
  10157. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  10158. var results = new Array();
  10159. for (var index = 0; index < uniformsNames.length; index++) {
  10160. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  10161. }
  10162. return results;
  10163. };
  10164. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  10165. var results = [];
  10166. for (var index = 0; index < attributesNames.length; index++) {
  10167. try {
  10168. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  10169. }
  10170. catch (e) {
  10171. results.push(-1);
  10172. }
  10173. }
  10174. return results;
  10175. };
  10176. Engine.prototype.enableEffect = function (effect) {
  10177. if (!effect) {
  10178. return;
  10179. }
  10180. // Use program
  10181. this.bindSamplers(effect);
  10182. this._currentEffect = effect;
  10183. if (effect.onBind) {
  10184. effect.onBind(effect);
  10185. }
  10186. effect.onBindObservable.notifyObservers(effect);
  10187. };
  10188. Engine.prototype.setIntArray = function (uniform, array) {
  10189. if (!uniform)
  10190. return;
  10191. this._gl.uniform1iv(uniform, array);
  10192. };
  10193. Engine.prototype.setIntArray2 = function (uniform, array) {
  10194. if (!uniform || array.length % 2 !== 0)
  10195. return;
  10196. this._gl.uniform2iv(uniform, array);
  10197. };
  10198. Engine.prototype.setIntArray3 = function (uniform, array) {
  10199. if (!uniform || array.length % 3 !== 0)
  10200. return;
  10201. this._gl.uniform3iv(uniform, array);
  10202. };
  10203. Engine.prototype.setIntArray4 = function (uniform, array) {
  10204. if (!uniform || array.length % 4 !== 0)
  10205. return;
  10206. this._gl.uniform4iv(uniform, array);
  10207. };
  10208. Engine.prototype.setFloatArray = function (uniform, array) {
  10209. if (!uniform)
  10210. return;
  10211. this._gl.uniform1fv(uniform, array);
  10212. };
  10213. Engine.prototype.setFloatArray2 = function (uniform, array) {
  10214. if (!uniform || array.length % 2 !== 0)
  10215. return;
  10216. this._gl.uniform2fv(uniform, array);
  10217. };
  10218. Engine.prototype.setFloatArray3 = function (uniform, array) {
  10219. if (!uniform || array.length % 3 !== 0)
  10220. return;
  10221. this._gl.uniform3fv(uniform, array);
  10222. };
  10223. Engine.prototype.setFloatArray4 = function (uniform, array) {
  10224. if (!uniform || array.length % 4 !== 0)
  10225. return;
  10226. this._gl.uniform4fv(uniform, array);
  10227. };
  10228. Engine.prototype.setArray = function (uniform, array) {
  10229. if (!uniform)
  10230. return;
  10231. this._gl.uniform1fv(uniform, array);
  10232. };
  10233. Engine.prototype.setArray2 = function (uniform, array) {
  10234. if (!uniform || array.length % 2 !== 0)
  10235. return;
  10236. this._gl.uniform2fv(uniform, array);
  10237. };
  10238. Engine.prototype.setArray3 = function (uniform, array) {
  10239. if (!uniform || array.length % 3 !== 0)
  10240. return;
  10241. this._gl.uniform3fv(uniform, array);
  10242. };
  10243. Engine.prototype.setArray4 = function (uniform, array) {
  10244. if (!uniform || array.length % 4 !== 0)
  10245. return;
  10246. this._gl.uniform4fv(uniform, array);
  10247. };
  10248. Engine.prototype.setMatrices = function (uniform, matrices) {
  10249. if (!uniform)
  10250. return;
  10251. this._gl.uniformMatrix4fv(uniform, false, matrices);
  10252. };
  10253. Engine.prototype.setMatrix = function (uniform, matrix) {
  10254. if (!uniform)
  10255. return;
  10256. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  10257. };
  10258. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  10259. if (!uniform)
  10260. return;
  10261. this._gl.uniformMatrix3fv(uniform, false, matrix);
  10262. };
  10263. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  10264. if (!uniform)
  10265. return;
  10266. this._gl.uniformMatrix2fv(uniform, false, matrix);
  10267. };
  10268. Engine.prototype.setInt = function (uniform, value) {
  10269. if (!uniform)
  10270. return;
  10271. this._gl.uniform1i(uniform, value);
  10272. };
  10273. Engine.prototype.setFloat = function (uniform, value) {
  10274. if (!uniform)
  10275. return;
  10276. this._gl.uniform1f(uniform, value);
  10277. };
  10278. Engine.prototype.setFloat2 = function (uniform, x, y) {
  10279. if (!uniform)
  10280. return;
  10281. this._gl.uniform2f(uniform, x, y);
  10282. };
  10283. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  10284. if (!uniform)
  10285. return;
  10286. this._gl.uniform3f(uniform, x, y, z);
  10287. };
  10288. Engine.prototype.setBool = function (uniform, bool) {
  10289. if (!uniform)
  10290. return;
  10291. this._gl.uniform1i(uniform, bool);
  10292. };
  10293. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  10294. if (!uniform)
  10295. return;
  10296. this._gl.uniform4f(uniform, x, y, z, w);
  10297. };
  10298. Engine.prototype.setColor3 = function (uniform, color3) {
  10299. if (!uniform)
  10300. return;
  10301. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  10302. };
  10303. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  10304. if (!uniform)
  10305. return;
  10306. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  10307. };
  10308. // States
  10309. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  10310. if (zOffset === void 0) { zOffset = 0; }
  10311. if (reverseSide === void 0) { reverseSide = false; }
  10312. // Culling
  10313. if (this._depthCullingState.cull !== culling || force) {
  10314. this._depthCullingState.cull = culling;
  10315. }
  10316. // Cull face
  10317. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  10318. if (this._depthCullingState.cullFace !== cullFace || force) {
  10319. this._depthCullingState.cullFace = cullFace;
  10320. }
  10321. // Z offset
  10322. this.setZOffset(zOffset);
  10323. // Front face
  10324. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  10325. if (this._depthCullingState.frontFace !== frontFace || force) {
  10326. this._depthCullingState.frontFace = frontFace;
  10327. }
  10328. };
  10329. Engine.prototype.setZOffset = function (value) {
  10330. this._depthCullingState.zOffset = value;
  10331. };
  10332. Engine.prototype.getZOffset = function () {
  10333. return this._depthCullingState.zOffset;
  10334. };
  10335. Engine.prototype.setDepthBuffer = function (enable) {
  10336. this._depthCullingState.depthTest = enable;
  10337. };
  10338. Engine.prototype.getDepthWrite = function () {
  10339. return this._depthCullingState.depthMask;
  10340. };
  10341. Engine.prototype.setDepthWrite = function (enable) {
  10342. this._depthCullingState.depthMask = enable;
  10343. };
  10344. Engine.prototype.setColorWrite = function (enable) {
  10345. this._gl.colorMask(enable, enable, enable, enable);
  10346. this._colorWrite = enable;
  10347. };
  10348. Engine.prototype.getColorWrite = function () {
  10349. return this._colorWrite;
  10350. };
  10351. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  10352. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  10353. };
  10354. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  10355. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  10356. if (this._alphaMode === mode) {
  10357. return;
  10358. }
  10359. switch (mode) {
  10360. case Engine.ALPHA_DISABLE:
  10361. this._alphaState.alphaBlend = false;
  10362. break;
  10363. case Engine.ALPHA_PREMULTIPLIED:
  10364. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  10365. this._alphaState.alphaBlend = true;
  10366. break;
  10367. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  10368. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  10369. this._alphaState.alphaBlend = true;
  10370. break;
  10371. case Engine.ALPHA_COMBINE:
  10372. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  10373. this._alphaState.alphaBlend = true;
  10374. break;
  10375. case Engine.ALPHA_ONEONE:
  10376. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  10377. this._alphaState.alphaBlend = true;
  10378. break;
  10379. case Engine.ALPHA_ADD:
  10380. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  10381. this._alphaState.alphaBlend = true;
  10382. break;
  10383. case Engine.ALPHA_SUBTRACT:
  10384. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  10385. this._alphaState.alphaBlend = true;
  10386. break;
  10387. case Engine.ALPHA_MULTIPLY:
  10388. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  10389. this._alphaState.alphaBlend = true;
  10390. break;
  10391. case Engine.ALPHA_MAXIMIZED:
  10392. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  10393. this._alphaState.alphaBlend = true;
  10394. break;
  10395. case Engine.ALPHA_INTERPOLATE:
  10396. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  10397. this._alphaState.alphaBlend = true;
  10398. break;
  10399. case Engine.ALPHA_SCREENMODE:
  10400. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  10401. this._alphaState.alphaBlend = true;
  10402. break;
  10403. }
  10404. if (!noDepthWriteChange) {
  10405. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  10406. }
  10407. this._alphaMode = mode;
  10408. };
  10409. Engine.prototype.getAlphaMode = function () {
  10410. return this._alphaMode;
  10411. };
  10412. Engine.prototype.setAlphaTesting = function (enable) {
  10413. this._alphaTest = enable;
  10414. };
  10415. Engine.prototype.getAlphaTesting = function () {
  10416. return !!this._alphaTest;
  10417. };
  10418. // Textures
  10419. Engine.prototype.wipeCaches = function (bruteForce) {
  10420. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  10421. return;
  10422. }
  10423. this._currentEffect = null;
  10424. // 6/8/2017: deltakosh: Should not be required anymore.
  10425. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  10426. if (bruteForce) {
  10427. this.resetTextureCache();
  10428. this._currentProgram = null;
  10429. this._stencilState.reset();
  10430. this._depthCullingState.reset();
  10431. this.setDepthFunctionToLessOrEqual();
  10432. this._alphaState.reset();
  10433. }
  10434. this._resetVertexBufferBinding();
  10435. this._cachedIndexBuffer = null;
  10436. this._cachedEffectForVertexBuffers = null;
  10437. this._unbindVertexArrayObject();
  10438. this.bindIndexBuffer(null);
  10439. };
  10440. /**
  10441. * Set the compressed texture format to use, based on the formats you have, and the formats
  10442. * supported by the hardware / browser.
  10443. *
  10444. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  10445. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  10446. * to API arguments needed to compressed textures. This puts the burden on the container
  10447. * generator to house the arcane code for determining these for current & future formats.
  10448. *
  10449. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  10450. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  10451. *
  10452. * Note: The result of this call is not taken into account when a texture is base64.
  10453. *
  10454. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  10455. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  10456. *
  10457. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  10458. * @returns The extension selected.
  10459. */
  10460. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  10461. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  10462. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  10463. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  10464. return this._textureFormatInUse = this._texturesSupported[i];
  10465. }
  10466. }
  10467. }
  10468. // actively set format to nothing, to allow this to be called more than once
  10469. // and possibly fail the 2nd time
  10470. this._textureFormatInUse = null;
  10471. return null;
  10472. };
  10473. Engine.prototype._createTexture = function () {
  10474. var texture = this._gl.createTexture();
  10475. if (!texture) {
  10476. throw new Error("Unable to create texture");
  10477. }
  10478. return texture;
  10479. };
  10480. /**
  10481. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  10482. * @param {string} urlArg- This contains one of the following:
  10483. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  10484. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  10485. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  10486. *
  10487. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  10488. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  10489. * @param {Scene} scene- Needed for loading to the correct scene.
  10490. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  10491. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  10492. * @param {callback} onError- Optional callback to be called upon failure.
  10493. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  10494. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  10495. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  10496. *
  10497. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  10498. */
  10499. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  10500. var _this = this;
  10501. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10502. if (onLoad === void 0) { onLoad = null; }
  10503. if (onError === void 0) { onError = null; }
  10504. if (buffer === void 0) { buffer = null; }
  10505. if (fallBack === void 0) { fallBack = null; }
  10506. if (format === void 0) { format = null; }
  10507. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  10508. var fromData = url.substr(0, 5) === "data:";
  10509. var fromBlob = url.substr(0, 5) === "blob:";
  10510. var isBase64 = fromData && url.indexOf("base64") !== -1;
  10511. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  10512. // establish the file extension, if possible
  10513. var lastDot = url.lastIndexOf('.');
  10514. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  10515. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  10516. var isTGA = (extension === ".tga");
  10517. // determine if a ktx file should be substituted
  10518. var isKTX = false;
  10519. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  10520. url = url.substring(0, lastDot) + this._textureFormatInUse;
  10521. isKTX = true;
  10522. }
  10523. if (scene) {
  10524. scene._addPendingData(texture);
  10525. }
  10526. texture.url = url;
  10527. texture.generateMipMaps = !noMipmap;
  10528. texture.samplingMode = samplingMode;
  10529. texture.invertY = invertY;
  10530. if (!this._doNotHandleContextLost) {
  10531. // Keep a link to the buffer only if we plan to handle context lost
  10532. texture._buffer = buffer;
  10533. }
  10534. var onLoadObserver = null;
  10535. if (onLoad && !fallBack) {
  10536. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  10537. }
  10538. if (!fallBack)
  10539. this._internalTexturesCache.push(texture);
  10540. var onerror = function (message, exception) {
  10541. if (scene) {
  10542. scene._removePendingData(texture);
  10543. }
  10544. if (onLoadObserver) {
  10545. texture.onLoadedObservable.remove(onLoadObserver);
  10546. }
  10547. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  10548. if (isKTX) {
  10549. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  10550. }
  10551. else if (BABYLON.Tools.UseFallbackTexture) {
  10552. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  10553. }
  10554. if (onError) {
  10555. onError(message || "Unknown error", exception);
  10556. }
  10557. };
  10558. var callback = null;
  10559. // processing for non-image formats
  10560. if (isKTX || isTGA || isDDS) {
  10561. if (isKTX) {
  10562. callback = function (data) {
  10563. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  10564. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  10565. ktx.uploadLevels(_this._gl, !noMipmap);
  10566. return false;
  10567. }, samplingMode);
  10568. };
  10569. }
  10570. else if (isTGA) {
  10571. callback = function (arrayBuffer) {
  10572. var data = new Uint8Array(arrayBuffer);
  10573. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  10574. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  10575. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  10576. return false;
  10577. }, samplingMode);
  10578. };
  10579. }
  10580. else if (isDDS) {
  10581. callback = function (data) {
  10582. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10583. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  10584. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  10585. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  10586. return false;
  10587. }, samplingMode);
  10588. };
  10589. }
  10590. if (!buffer) {
  10591. this._loadFile(url, function (data) {
  10592. if (callback) {
  10593. callback(data);
  10594. }
  10595. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  10596. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  10597. });
  10598. }
  10599. else {
  10600. if (callback) {
  10601. callback(buffer);
  10602. }
  10603. }
  10604. // image format processing
  10605. }
  10606. else {
  10607. var onload = function (img) {
  10608. if (fromBlob && !_this._doNotHandleContextLost) {
  10609. // We need to store the image if we need to rebuild the texture
  10610. // in case of a webgl context lost
  10611. texture._buffer = img;
  10612. }
  10613. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  10614. var gl = _this._gl;
  10615. var isPot = (img.width === potWidth && img.height === potHeight);
  10616. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  10617. if (isPot) {
  10618. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10619. return false;
  10620. }
  10621. // Using shaders to rescale because canvas.drawImage is lossy
  10622. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10623. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  10624. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10625. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10626. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10627. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10628. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10629. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  10630. _this._releaseTexture(source);
  10631. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  10632. continuationCallback();
  10633. });
  10634. return true;
  10635. }, samplingMode);
  10636. };
  10637. if (!fromData || isBase64)
  10638. if (buffer instanceof HTMLImageElement) {
  10639. onload(buffer);
  10640. }
  10641. else {
  10642. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10643. }
  10644. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  10645. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  10646. else
  10647. onload(buffer);
  10648. }
  10649. return texture;
  10650. };
  10651. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  10652. var _this = this;
  10653. var rtt = this.createRenderTargetTexture({
  10654. width: destination.width,
  10655. height: destination.height,
  10656. }, {
  10657. generateMipMaps: false,
  10658. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  10659. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  10660. generateDepthBuffer: false,
  10661. generateStencilBuffer: false
  10662. });
  10663. if (!this._rescalePostProcess) {
  10664. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  10665. }
  10666. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  10667. _this._rescalePostProcess.onApply = function (effect) {
  10668. effect._bindTexture("textureSampler", source);
  10669. };
  10670. var hostingScene = scene;
  10671. if (!hostingScene) {
  10672. hostingScene = _this.scenes[_this.scenes.length - 1];
  10673. }
  10674. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  10675. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  10676. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  10677. _this.unBindFramebuffer(rtt);
  10678. _this._releaseTexture(rtt);
  10679. if (onComplete) {
  10680. onComplete();
  10681. }
  10682. });
  10683. };
  10684. Engine.prototype._getInternalFormat = function (format) {
  10685. var internalFormat = this._gl.RGBA;
  10686. switch (format) {
  10687. case Engine.TEXTUREFORMAT_ALPHA:
  10688. internalFormat = this._gl.ALPHA;
  10689. break;
  10690. case Engine.TEXTUREFORMAT_LUMINANCE:
  10691. internalFormat = this._gl.LUMINANCE;
  10692. break;
  10693. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  10694. internalFormat = this._gl.LUMINANCE_ALPHA;
  10695. break;
  10696. case Engine.TEXTUREFORMAT_RGB:
  10697. internalFormat = this._gl.RGB;
  10698. break;
  10699. case Engine.TEXTUREFORMAT_RGBA:
  10700. internalFormat = this._gl.RGBA;
  10701. break;
  10702. }
  10703. return internalFormat;
  10704. };
  10705. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  10706. if (compression === void 0) { compression = null; }
  10707. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  10708. if (!texture) {
  10709. return;
  10710. }
  10711. var internalFormat = this._getInternalFormat(format);
  10712. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10713. var textureType = this._getWebGLTextureType(type);
  10714. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  10715. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10716. if (!this._doNotHandleContextLost) {
  10717. texture._bufferView = data;
  10718. texture.format = format;
  10719. texture.type = type;
  10720. texture.invertY = invertY;
  10721. texture._compression = compression;
  10722. }
  10723. if (texture.width % 4 !== 0) {
  10724. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  10725. }
  10726. if (compression && data) {
  10727. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  10728. }
  10729. else {
  10730. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  10731. }
  10732. if (texture.generateMipMaps) {
  10733. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10734. }
  10735. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10736. // this.resetTextureCache();
  10737. texture.isReady = true;
  10738. };
  10739. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  10740. if (compression === void 0) { compression = null; }
  10741. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  10742. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  10743. texture.baseWidth = width;
  10744. texture.baseHeight = height;
  10745. texture.width = width;
  10746. texture.height = height;
  10747. texture.format = format;
  10748. texture.generateMipMaps = generateMipMaps;
  10749. texture.samplingMode = samplingMode;
  10750. texture.invertY = invertY;
  10751. texture._compression = compression;
  10752. texture.type = type;
  10753. if (!this._doNotHandleContextLost) {
  10754. texture._bufferView = data;
  10755. }
  10756. this.updateRawTexture(texture, data, format, invertY, compression, type);
  10757. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  10758. // Filters
  10759. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  10760. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10761. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10762. if (generateMipMaps) {
  10763. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10764. }
  10765. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10766. this._internalTexturesCache.push(texture);
  10767. return texture;
  10768. };
  10769. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  10770. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  10771. texture.baseWidth = width;
  10772. texture.baseHeight = height;
  10773. if (generateMipMaps) {
  10774. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  10775. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  10776. }
  10777. // this.resetTextureCache();
  10778. texture.width = width;
  10779. texture.height = height;
  10780. texture.isReady = false;
  10781. texture.generateMipMaps = generateMipMaps;
  10782. texture.samplingMode = samplingMode;
  10783. this.updateTextureSamplingMode(samplingMode, texture);
  10784. this._internalTexturesCache.push(texture);
  10785. return texture;
  10786. };
  10787. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  10788. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  10789. if (texture.isCube) {
  10790. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  10791. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10792. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10793. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10794. }
  10795. else if (texture.is3D) {
  10796. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  10797. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10798. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10799. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  10800. }
  10801. else {
  10802. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  10803. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10804. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10805. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10806. }
  10807. texture.samplingMode = samplingMode;
  10808. };
  10809. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  10810. if (premulAlpha === void 0) { premulAlpha = false; }
  10811. if (!texture) {
  10812. return;
  10813. }
  10814. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  10815. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  10816. if (premulAlpha) {
  10817. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  10818. }
  10819. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  10820. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  10821. if (texture.generateMipMaps) {
  10822. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10823. }
  10824. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10825. if (premulAlpha) {
  10826. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  10827. }
  10828. texture.isReady = true;
  10829. };
  10830. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  10831. if (!texture || texture._isDisabled) {
  10832. return;
  10833. }
  10834. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  10835. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  10836. try {
  10837. // Testing video texture support
  10838. if (this._videoTextureSupported === undefined) {
  10839. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10840. if (this._gl.getError() !== 0) {
  10841. this._videoTextureSupported = false;
  10842. }
  10843. else {
  10844. this._videoTextureSupported = true;
  10845. }
  10846. }
  10847. // Copy video through the current working canvas if video texture is not supported
  10848. if (!this._videoTextureSupported) {
  10849. if (!texture._workingCanvas) {
  10850. texture._workingCanvas = document.createElement("canvas");
  10851. var context = texture._workingCanvas.getContext("2d");
  10852. if (!context) {
  10853. throw new Error("Unable to get 2d context");
  10854. }
  10855. texture._workingContext = context;
  10856. texture._workingCanvas.width = texture.width;
  10857. texture._workingCanvas.height = texture.height;
  10858. }
  10859. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  10860. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  10861. }
  10862. else {
  10863. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10864. }
  10865. if (texture.generateMipMaps) {
  10866. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10867. }
  10868. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10869. // this.resetTextureCache();
  10870. texture.isReady = true;
  10871. }
  10872. catch (ex) {
  10873. // Something unexpected
  10874. // Let's disable the texture
  10875. texture._isDisabled = true;
  10876. }
  10877. };
  10878. Engine.prototype.createRenderTargetTexture = function (size, options) {
  10879. var fullOptions = new RenderTargetCreationOptions();
  10880. if (options !== undefined && typeof options === "object") {
  10881. fullOptions.generateMipMaps = options.generateMipMaps;
  10882. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10883. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  10884. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  10885. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  10886. }
  10887. else {
  10888. fullOptions.generateMipMaps = options;
  10889. fullOptions.generateDepthBuffer = true;
  10890. fullOptions.generateStencilBuffer = false;
  10891. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10892. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10893. }
  10894. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10895. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10896. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10897. }
  10898. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10899. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10900. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10901. }
  10902. var gl = this._gl;
  10903. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10904. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  10905. var width = size.width || size;
  10906. var height = size.height || size;
  10907. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  10908. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10909. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10910. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10911. }
  10912. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10913. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10914. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10915. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10916. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  10917. // Create the framebuffer
  10918. var framebuffer = gl.createFramebuffer();
  10919. this.bindUnboundFramebuffer(framebuffer);
  10920. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10921. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  10922. if (fullOptions.generateMipMaps) {
  10923. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10924. }
  10925. // Unbind
  10926. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10927. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10928. this.bindUnboundFramebuffer(null);
  10929. texture._framebuffer = framebuffer;
  10930. texture.baseWidth = width;
  10931. texture.baseHeight = height;
  10932. texture.width = width;
  10933. texture.height = height;
  10934. texture.isReady = true;
  10935. texture.samples = 1;
  10936. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  10937. texture.samplingMode = fullOptions.samplingMode;
  10938. texture.type = fullOptions.type;
  10939. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  10940. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  10941. // this.resetTextureCache();
  10942. this._internalTexturesCache.push(texture);
  10943. return texture;
  10944. };
  10945. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  10946. var generateMipMaps = false;
  10947. var generateDepthBuffer = true;
  10948. var generateStencilBuffer = false;
  10949. var generateDepthTexture = false;
  10950. var textureCount = 1;
  10951. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  10952. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10953. var types = [], samplingModes = [];
  10954. if (options !== undefined) {
  10955. generateMipMaps = options.generateMipMaps;
  10956. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10957. generateStencilBuffer = options.generateStencilBuffer;
  10958. generateDepthTexture = options.generateDepthTexture;
  10959. textureCount = options.textureCount || 1;
  10960. if (options.types) {
  10961. types = options.types;
  10962. }
  10963. if (options.samplingModes) {
  10964. samplingModes = options.samplingModes;
  10965. }
  10966. }
  10967. var gl = this._gl;
  10968. // Create the framebuffer
  10969. var framebuffer = gl.createFramebuffer();
  10970. this.bindUnboundFramebuffer(framebuffer);
  10971. var width = size.width || size;
  10972. var height = size.height || size;
  10973. var textures = [];
  10974. var attachments = [];
  10975. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  10976. for (var i = 0; i < textureCount; i++) {
  10977. var samplingMode = samplingModes[i] || defaultSamplingMode;
  10978. var type = types[i] || defaultType;
  10979. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10980. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10981. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10982. }
  10983. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10984. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10985. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10986. }
  10987. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10988. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10989. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10990. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10991. }
  10992. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10993. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10994. textures.push(texture);
  10995. attachments.push(attachment);
  10996. gl.activeTexture(gl["TEXTURE" + i]);
  10997. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  10998. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10999. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11000. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11001. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11002. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  11003. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11004. if (generateMipMaps) {
  11005. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11006. }
  11007. // Unbind
  11008. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11009. texture._framebuffer = framebuffer;
  11010. texture._depthStencilBuffer = depthStencilBuffer;
  11011. texture.baseWidth = width;
  11012. texture.baseHeight = height;
  11013. texture.width = width;
  11014. texture.height = height;
  11015. texture.isReady = true;
  11016. texture.samples = 1;
  11017. texture.generateMipMaps = generateMipMaps;
  11018. texture.samplingMode = samplingMode;
  11019. texture.type = type;
  11020. texture._generateDepthBuffer = generateDepthBuffer;
  11021. texture._generateStencilBuffer = generateStencilBuffer;
  11022. texture._attachments = attachments;
  11023. this._internalTexturesCache.push(texture);
  11024. }
  11025. if (generateDepthTexture && this._caps.depthTextureExtension) {
  11026. // Depth texture
  11027. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  11028. gl.activeTexture(gl.TEXTURE0);
  11029. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  11030. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11031. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11032. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11033. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11034. 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);
  11035. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  11036. depthTexture._framebuffer = framebuffer;
  11037. depthTexture.baseWidth = width;
  11038. depthTexture.baseHeight = height;
  11039. depthTexture.width = width;
  11040. depthTexture.height = height;
  11041. depthTexture.isReady = true;
  11042. depthTexture.samples = 1;
  11043. depthTexture.generateMipMaps = generateMipMaps;
  11044. depthTexture.samplingMode = gl.NEAREST;
  11045. depthTexture._generateDepthBuffer = generateDepthBuffer;
  11046. depthTexture._generateStencilBuffer = generateStencilBuffer;
  11047. textures.push(depthTexture);
  11048. this._internalTexturesCache.push(depthTexture);
  11049. }
  11050. gl.drawBuffers(attachments);
  11051. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11052. this.bindUnboundFramebuffer(null);
  11053. this.resetTextureCache();
  11054. return textures;
  11055. };
  11056. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  11057. if (samples === void 0) { samples = 1; }
  11058. var depthStencilBuffer = null;
  11059. var gl = this._gl;
  11060. // Create the depth/stencil buffer
  11061. if (generateStencilBuffer) {
  11062. depthStencilBuffer = gl.createRenderbuffer();
  11063. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  11064. if (samples > 1) {
  11065. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  11066. }
  11067. else {
  11068. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  11069. }
  11070. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  11071. }
  11072. else if (generateDepthBuffer) {
  11073. depthStencilBuffer = gl.createRenderbuffer();
  11074. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  11075. if (samples > 1) {
  11076. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  11077. }
  11078. else {
  11079. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  11080. }
  11081. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  11082. }
  11083. return depthStencilBuffer;
  11084. };
  11085. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  11086. if (this.webGLVersion < 2 || !texture) {
  11087. return 1;
  11088. }
  11089. if (texture.samples === samples) {
  11090. return samples;
  11091. }
  11092. var gl = this._gl;
  11093. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  11094. // Dispose previous render buffers
  11095. if (texture._depthStencilBuffer) {
  11096. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  11097. texture._depthStencilBuffer = null;
  11098. }
  11099. if (texture._MSAAFramebuffer) {
  11100. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  11101. texture._MSAAFramebuffer = null;
  11102. }
  11103. if (texture._MSAARenderBuffer) {
  11104. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  11105. texture._MSAARenderBuffer = null;
  11106. }
  11107. if (samples > 1) {
  11108. var framebuffer = gl.createFramebuffer();
  11109. if (!framebuffer) {
  11110. throw new Error("Unable to create multi sampled framebuffer");
  11111. }
  11112. texture._MSAAFramebuffer = framebuffer;
  11113. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  11114. var colorRenderbuffer = gl.createRenderbuffer();
  11115. if (!colorRenderbuffer) {
  11116. throw new Error("Unable to create multi sampled framebuffer");
  11117. }
  11118. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  11119. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  11120. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  11121. texture._MSAARenderBuffer = colorRenderbuffer;
  11122. }
  11123. else {
  11124. this.bindUnboundFramebuffer(texture._framebuffer);
  11125. }
  11126. texture.samples = samples;
  11127. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  11128. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11129. this.bindUnboundFramebuffer(null);
  11130. return samples;
  11131. };
  11132. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  11133. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  11134. return 1;
  11135. }
  11136. if (textures[0].samples === samples) {
  11137. return samples;
  11138. }
  11139. var gl = this._gl;
  11140. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  11141. // Dispose previous render buffers
  11142. if (textures[0]._depthStencilBuffer) {
  11143. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  11144. textures[0]._depthStencilBuffer = null;
  11145. }
  11146. if (textures[0]._MSAAFramebuffer) {
  11147. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  11148. textures[0]._MSAAFramebuffer = null;
  11149. }
  11150. for (var i = 0; i < textures.length; i++) {
  11151. if (textures[i]._MSAARenderBuffer) {
  11152. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  11153. textures[i]._MSAARenderBuffer = null;
  11154. }
  11155. }
  11156. if (samples > 1) {
  11157. var framebuffer = gl.createFramebuffer();
  11158. if (!framebuffer) {
  11159. throw new Error("Unable to create multi sampled framebuffer");
  11160. }
  11161. this.bindUnboundFramebuffer(framebuffer);
  11162. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  11163. var attachments = [];
  11164. for (var i = 0; i < textures.length; i++) {
  11165. var texture = textures[i];
  11166. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11167. var colorRenderbuffer = gl.createRenderbuffer();
  11168. if (!colorRenderbuffer) {
  11169. throw new Error("Unable to create multi sampled framebuffer");
  11170. }
  11171. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  11172. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  11173. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  11174. texture._MSAAFramebuffer = framebuffer;
  11175. texture._MSAARenderBuffer = colorRenderbuffer;
  11176. texture.samples = samples;
  11177. texture._depthStencilBuffer = depthStencilBuffer;
  11178. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11179. attachments.push(attachment);
  11180. }
  11181. gl.drawBuffers(attachments);
  11182. }
  11183. else {
  11184. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  11185. }
  11186. this.bindUnboundFramebuffer(null);
  11187. return samples;
  11188. };
  11189. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  11190. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  11191. };
  11192. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  11193. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  11194. };
  11195. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  11196. var gl = this._gl;
  11197. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  11198. var generateMipMaps = true;
  11199. var generateDepthBuffer = true;
  11200. var generateStencilBuffer = false;
  11201. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  11202. if (options !== undefined) {
  11203. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  11204. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  11205. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  11206. if (options.samplingMode !== undefined) {
  11207. samplingMode = options.samplingMode;
  11208. }
  11209. }
  11210. texture.isCube = true;
  11211. texture.generateMipMaps = generateMipMaps;
  11212. texture.samples = 1;
  11213. texture.samplingMode = samplingMode;
  11214. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  11215. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  11216. for (var face = 0; face < 6; face++) {
  11217. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  11218. }
  11219. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  11220. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  11221. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11222. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11223. // Create the framebuffer
  11224. var framebuffer = gl.createFramebuffer();
  11225. this.bindUnboundFramebuffer(framebuffer);
  11226. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  11227. // Mipmaps
  11228. if (texture.generateMipMaps) {
  11229. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11230. }
  11231. // Unbind
  11232. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11233. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11234. this.bindUnboundFramebuffer(null);
  11235. texture._framebuffer = framebuffer;
  11236. texture.width = size;
  11237. texture.height = size;
  11238. texture.isReady = true;
  11239. //this.resetTextureCache();
  11240. this._internalTexturesCache.push(texture);
  11241. return texture;
  11242. };
  11243. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  11244. var _this = this;
  11245. if (onLoad === void 0) { onLoad = null; }
  11246. if (onError === void 0) { onError = null; }
  11247. if (forcedExtension === void 0) { forcedExtension = null; }
  11248. var callback = function (loadData) {
  11249. if (!loadData) {
  11250. if (onLoad) {
  11251. onLoad(null);
  11252. }
  11253. return;
  11254. }
  11255. var texture = loadData.texture;
  11256. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  11257. texture._lodGenerationScale = scale;
  11258. texture._lodGenerationOffset = offset;
  11259. if (_this._caps.textureLOD) {
  11260. // Do not add extra process if texture lod is supported.
  11261. if (onLoad) {
  11262. onLoad(texture);
  11263. }
  11264. return;
  11265. }
  11266. var mipSlices = 3;
  11267. var gl = _this._gl;
  11268. var width = loadData.width;
  11269. if (!width) {
  11270. return;
  11271. }
  11272. var textures = [];
  11273. for (var i = 0; i < mipSlices; i++) {
  11274. //compute LOD from even spacing in smoothness (matching shader calculation)
  11275. var smoothness = i / (mipSlices - 1);
  11276. var roughness = 1 - smoothness;
  11277. var minLODIndex = offset; // roughness = 0
  11278. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  11279. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  11280. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  11281. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  11282. glTextureFromLod.isCube = true;
  11283. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  11284. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  11285. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  11286. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11287. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11288. if (loadData.isDDS) {
  11289. var info = loadData.info;
  11290. var data = loadData.data;
  11291. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  11292. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  11293. }
  11294. else {
  11295. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  11296. }
  11297. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11298. // Wrap in a base texture for easy binding.
  11299. var lodTexture = new BABYLON.BaseTexture(scene);
  11300. lodTexture.isCube = true;
  11301. lodTexture._texture = glTextureFromLod;
  11302. glTextureFromLod.isReady = true;
  11303. textures.push(lodTexture);
  11304. }
  11305. texture._lodTextureHigh = textures[2];
  11306. texture._lodTextureMid = textures[1];
  11307. texture._lodTextureLow = textures[0];
  11308. if (onLoad) {
  11309. onLoad(texture);
  11310. }
  11311. };
  11312. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  11313. };
  11314. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  11315. var _this = this;
  11316. if (onLoad === void 0) { onLoad = null; }
  11317. if (onError === void 0) { onError = null; }
  11318. if (forcedExtension === void 0) { forcedExtension = null; }
  11319. var gl = this._gl;
  11320. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  11321. texture.isCube = true;
  11322. texture.url = rootUrl;
  11323. texture.generateMipMaps = !noMipmap;
  11324. if (!this._doNotHandleContextLost) {
  11325. texture._extension = forcedExtension;
  11326. texture._files = files;
  11327. }
  11328. var isKTX = false;
  11329. var isDDS = false;
  11330. var lastDot = rootUrl.lastIndexOf('.');
  11331. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  11332. if (this._textureFormatInUse) {
  11333. extension = this._textureFormatInUse;
  11334. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  11335. isKTX = true;
  11336. }
  11337. else {
  11338. isDDS = (extension === ".dds");
  11339. }
  11340. var onerror = function (request, exception) {
  11341. if (onError && request) {
  11342. onError(request.status + " " + request.statusText, exception);
  11343. }
  11344. };
  11345. if (isKTX) {
  11346. this._loadFile(rootUrl, function (data) {
  11347. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  11348. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  11349. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  11350. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  11351. ktx.uploadLevels(_this._gl, !noMipmap);
  11352. _this.setCubeMapTextureParams(gl, loadMipmap);
  11353. texture.width = ktx.pixelWidth;
  11354. texture.height = ktx.pixelHeight;
  11355. texture.isReady = true;
  11356. }, undefined, undefined, true, onerror);
  11357. }
  11358. else if (isDDS) {
  11359. if (files && files.length === 6) {
  11360. this._cascadeLoadFiles(rootUrl, scene, function (imgs) {
  11361. var info;
  11362. var loadMipmap = false;
  11363. var width = 0;
  11364. for (var index = 0; index < imgs.length; index++) {
  11365. var data = imgs[index];
  11366. info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  11367. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  11368. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  11369. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  11370. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  11371. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  11372. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11373. }
  11374. texture.width = info.width;
  11375. texture.height = info.height;
  11376. texture.type = info.textureType;
  11377. width = info.width;
  11378. }
  11379. _this.setCubeMapTextureParams(gl, loadMipmap);
  11380. texture.isReady = true;
  11381. if (onLoad) {
  11382. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  11383. }
  11384. }, files, onError);
  11385. }
  11386. else {
  11387. this._loadFile(rootUrl, function (data) {
  11388. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  11389. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  11390. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  11391. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  11392. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  11393. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  11394. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11395. }
  11396. _this.setCubeMapTextureParams(gl, loadMipmap);
  11397. texture.width = info.width;
  11398. texture.height = info.height;
  11399. texture.isReady = true;
  11400. texture.type = info.textureType;
  11401. if (onLoad) {
  11402. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  11403. }
  11404. }, undefined, undefined, true, onerror);
  11405. }
  11406. }
  11407. else {
  11408. if (!files) {
  11409. throw new Error("Cannot load cubemap because files were not defined");
  11410. }
  11411. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  11412. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  11413. var height = width;
  11414. _this._prepareWorkingCanvas();
  11415. if (!_this._workingCanvas || !_this._workingContext) {
  11416. return;
  11417. }
  11418. _this._workingCanvas.width = width;
  11419. _this._workingCanvas.height = height;
  11420. var faces = [
  11421. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  11422. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  11423. ];
  11424. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  11425. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  11426. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  11427. for (var index = 0; index < faces.length; index++) {
  11428. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  11429. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  11430. }
  11431. if (!noMipmap) {
  11432. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11433. }
  11434. _this.setCubeMapTextureParams(gl, !noMipmap);
  11435. texture.width = width;
  11436. texture.height = height;
  11437. texture.isReady = true;
  11438. if (format) {
  11439. texture.format = format;
  11440. }
  11441. texture.onLoadedObservable.notifyObservers(texture);
  11442. texture.onLoadedObservable.clear();
  11443. if (onLoad) {
  11444. onLoad();
  11445. }
  11446. }, files, onError);
  11447. }
  11448. this._internalTexturesCache.push(texture);
  11449. return texture;
  11450. };
  11451. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  11452. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  11453. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  11454. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11455. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11456. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11457. // this.resetTextureCache();
  11458. };
  11459. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  11460. if (compression === void 0) { compression = null; }
  11461. if (level === void 0) { level = 0; }
  11462. texture._bufferViewArray = data;
  11463. texture.format = format;
  11464. texture.type = type;
  11465. texture.invertY = invertY;
  11466. texture._compression = compression;
  11467. var gl = this._gl;
  11468. var textureType = this._getWebGLTextureType(type);
  11469. var internalFormat = this._getInternalFormat(format);
  11470. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  11471. var needConversion = false;
  11472. if (internalFormat === gl.RGB) {
  11473. internalFormat = gl.RGBA;
  11474. needConversion = true;
  11475. }
  11476. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  11477. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11478. if (texture.width % 4 !== 0) {
  11479. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  11480. }
  11481. // Data are known to be in +X +Y +Z -X -Y -Z
  11482. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  11483. var faceData = data[faceIndex];
  11484. if (compression) {
  11485. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  11486. }
  11487. else {
  11488. if (needConversion) {
  11489. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  11490. }
  11491. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  11492. }
  11493. }
  11494. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  11495. if (isPot && texture.generateMipMaps && level === 0) {
  11496. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  11497. }
  11498. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11499. // this.resetTextureCache();
  11500. texture.isReady = true;
  11501. };
  11502. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  11503. if (compression === void 0) { compression = null; }
  11504. var gl = this._gl;
  11505. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  11506. texture.isCube = true;
  11507. texture.generateMipMaps = generateMipMaps;
  11508. texture.format = format;
  11509. texture.type = type;
  11510. if (!this._doNotHandleContextLost) {
  11511. texture._bufferViewArray = data;
  11512. }
  11513. var textureType = this._getWebGLTextureType(type);
  11514. var internalFormat = this._getInternalFormat(format);
  11515. if (internalFormat === gl.RGB) {
  11516. internalFormat = gl.RGBA;
  11517. }
  11518. var width = size;
  11519. var height = width;
  11520. texture.width = width;
  11521. texture.height = height;
  11522. // Double check on POT to generate Mips.
  11523. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  11524. if (!isPot) {
  11525. generateMipMaps = false;
  11526. }
  11527. // Upload data if needed. The texture won't be ready until then.
  11528. if (data) {
  11529. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  11530. }
  11531. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  11532. // Filters
  11533. if (data && generateMipMaps) {
  11534. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  11535. }
  11536. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  11537. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11538. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11539. }
  11540. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  11541. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11542. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11543. }
  11544. else {
  11545. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  11546. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  11547. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  11548. }
  11549. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11550. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11551. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11552. return texture;
  11553. };
  11554. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  11555. var _this = this;
  11556. if (onLoad === void 0) { onLoad = null; }
  11557. if (onError === void 0) { onError = null; }
  11558. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11559. if (invertY === void 0) { invertY = false; }
  11560. var gl = this._gl;
  11561. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  11562. scene._addPendingData(texture);
  11563. texture.url = url;
  11564. this._internalTexturesCache.push(texture);
  11565. var onerror = function (request, exception) {
  11566. scene._removePendingData(texture);
  11567. if (onError && request) {
  11568. onError(request.status + " " + request.statusText, exception);
  11569. }
  11570. };
  11571. var internalCallback = function (data) {
  11572. var width = texture.width;
  11573. var faceDataArrays = callback(data);
  11574. if (!faceDataArrays) {
  11575. return;
  11576. }
  11577. if (mipmmapGenerator) {
  11578. var textureType = _this._getWebGLTextureType(type);
  11579. var internalFormat = _this._getInternalFormat(format);
  11580. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  11581. var needConversion = false;
  11582. if (internalFormat === gl.RGB) {
  11583. internalFormat = gl.RGBA;
  11584. needConversion = true;
  11585. }
  11586. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  11587. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  11588. var mipData = mipmmapGenerator(faceDataArrays);
  11589. for (var level = 0; level < mipData.length; level++) {
  11590. var mipSize = width >> level;
  11591. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  11592. var mipFaceData = mipData[level][faceIndex];
  11593. if (needConversion) {
  11594. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  11595. }
  11596. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  11597. }
  11598. }
  11599. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11600. }
  11601. else {
  11602. texture.generateMipMaps = !noMipmap;
  11603. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  11604. }
  11605. texture.isReady = true;
  11606. // this.resetTextureCache();
  11607. scene._removePendingData(texture);
  11608. if (onLoad) {
  11609. onLoad();
  11610. }
  11611. };
  11612. this._loadFile(url, function (data) {
  11613. internalCallback(data);
  11614. }, undefined, scene.database, true, onerror);
  11615. return texture;
  11616. };
  11617. ;
  11618. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  11619. if (compression === void 0) { compression = null; }
  11620. var internalFormat = this._getInternalFormat(format);
  11621. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  11622. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11623. if (!this._doNotHandleContextLost) {
  11624. texture._bufferView = data;
  11625. texture.format = format;
  11626. texture.invertY = invertY;
  11627. texture._compression = compression;
  11628. }
  11629. if (texture.width % 4 !== 0) {
  11630. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  11631. }
  11632. if (compression && data) {
  11633. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  11634. }
  11635. else {
  11636. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  11637. }
  11638. if (texture.generateMipMaps) {
  11639. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  11640. }
  11641. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11642. // this.resetTextureCache();
  11643. texture.isReady = true;
  11644. };
  11645. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  11646. if (compression === void 0) { compression = null; }
  11647. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  11648. texture.baseWidth = width;
  11649. texture.baseHeight = height;
  11650. texture.baseDepth = depth;
  11651. texture.width = width;
  11652. texture.height = height;
  11653. texture.depth = depth;
  11654. texture.format = format;
  11655. texture.generateMipMaps = generateMipMaps;
  11656. texture.samplingMode = samplingMode;
  11657. texture.is3D = true;
  11658. if (!this._doNotHandleContextLost) {
  11659. texture._bufferView = data;
  11660. }
  11661. this.updateRawTexture3D(texture, data, format, invertY, compression);
  11662. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  11663. // Filters
  11664. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  11665. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11666. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11667. if (generateMipMaps) {
  11668. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  11669. }
  11670. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11671. this._internalTexturesCache.push(texture);
  11672. return texture;
  11673. };
  11674. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  11675. var gl = this._gl;
  11676. if (!gl) {
  11677. return;
  11678. }
  11679. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  11680. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11681. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11682. if (!noMipmap && !isCompressed) {
  11683. gl.generateMipmap(gl.TEXTURE_2D);
  11684. }
  11685. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11686. // this.resetTextureCache();
  11687. if (scene) {
  11688. scene._removePendingData(texture);
  11689. }
  11690. texture.onLoadedObservable.notifyObservers(texture);
  11691. texture.onLoadedObservable.clear();
  11692. };
  11693. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  11694. var _this = this;
  11695. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11696. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  11697. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  11698. var gl = this._gl;
  11699. if (!gl) {
  11700. return;
  11701. }
  11702. if (!texture._webGLTexture) {
  11703. // this.resetTextureCache();
  11704. if (scene) {
  11705. scene._removePendingData(texture);
  11706. }
  11707. return;
  11708. }
  11709. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11710. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11711. texture.baseWidth = width;
  11712. texture.baseHeight = height;
  11713. texture.width = potWidth;
  11714. texture.height = potHeight;
  11715. texture.isReady = true;
  11716. if (processFunction(potWidth, potHeight, function () {
  11717. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11718. })) {
  11719. // Returning as texture needs extra async steps
  11720. return;
  11721. }
  11722. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11723. };
  11724. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  11725. // Create new RGBA data container.
  11726. var rgbaData;
  11727. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  11728. rgbaData = new Float32Array(width * height * 4);
  11729. }
  11730. else {
  11731. rgbaData = new Uint32Array(width * height * 4);
  11732. }
  11733. // Convert each pixel.
  11734. for (var x = 0; x < width; x++) {
  11735. for (var y = 0; y < height; y++) {
  11736. var index = (y * width + x) * 3;
  11737. var newIndex = (y * width + x) * 4;
  11738. // Map Old Value to new value.
  11739. rgbaData[newIndex + 0] = rgbData[index + 0];
  11740. rgbaData[newIndex + 1] = rgbData[index + 1];
  11741. rgbaData[newIndex + 2] = rgbData[index + 2];
  11742. // Add fully opaque alpha channel.
  11743. rgbaData[newIndex + 3] = 1;
  11744. }
  11745. }
  11746. return rgbaData;
  11747. };
  11748. Engine.prototype._releaseFramebufferObjects = function (texture) {
  11749. var gl = this._gl;
  11750. if (texture._framebuffer) {
  11751. gl.deleteFramebuffer(texture._framebuffer);
  11752. texture._framebuffer = null;
  11753. }
  11754. if (texture._depthStencilBuffer) {
  11755. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  11756. texture._depthStencilBuffer = null;
  11757. }
  11758. if (texture._MSAAFramebuffer) {
  11759. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  11760. texture._MSAAFramebuffer = null;
  11761. }
  11762. if (texture._MSAARenderBuffer) {
  11763. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  11764. texture._MSAARenderBuffer = null;
  11765. }
  11766. };
  11767. Engine.prototype._releaseTexture = function (texture) {
  11768. var gl = this._gl;
  11769. this._releaseFramebufferObjects(texture);
  11770. gl.deleteTexture(texture._webGLTexture);
  11771. // Unbind channels
  11772. this.unbindAllTextures();
  11773. var index = this._internalTexturesCache.indexOf(texture);
  11774. if (index !== -1) {
  11775. this._internalTexturesCache.splice(index, 1);
  11776. }
  11777. // Integrated fixed lod samplers.
  11778. if (texture._lodTextureHigh) {
  11779. texture._lodTextureHigh.dispose();
  11780. }
  11781. if (texture._lodTextureMid) {
  11782. texture._lodTextureMid.dispose();
  11783. }
  11784. if (texture._lodTextureLow) {
  11785. texture._lodTextureLow.dispose();
  11786. }
  11787. };
  11788. Engine.prototype.setProgram = function (program) {
  11789. if (this._currentProgram !== program) {
  11790. this._gl.useProgram(program);
  11791. this._currentProgram = program;
  11792. }
  11793. };
  11794. Engine.prototype.bindSamplers = function (effect) {
  11795. this.setProgram(effect.getProgram());
  11796. var samplers = effect.getSamplers();
  11797. for (var index = 0; index < samplers.length; index++) {
  11798. var uniform = effect.getUniform(samplers[index]);
  11799. if (uniform) {
  11800. this._boundUniforms[index] = uniform;
  11801. }
  11802. }
  11803. this._currentEffect = null;
  11804. };
  11805. Engine.prototype._activateTextureChannel = function (channel) {
  11806. if (this._activeChannel !== channel && channel > -1) {
  11807. this._gl.activeTexture(this._gl.TEXTURE0 + channel);
  11808. this._activeChannel = channel;
  11809. }
  11810. };
  11811. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  11812. var index = this._boundTexturesStack.indexOf(internalTexture);
  11813. if (index > -1 && index !== this._boundTexturesStack.length - 1) {
  11814. this._boundTexturesStack.splice(index, 1);
  11815. this._boundTexturesStack.push(internalTexture);
  11816. }
  11817. };
  11818. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  11819. var currentSlot = internalTexture._designatedSlot;
  11820. internalTexture._designatedSlot = -1;
  11821. var index = this._boundTexturesStack.indexOf(internalTexture);
  11822. if (index > -1) {
  11823. this._boundTexturesStack.splice(index, 1);
  11824. if (currentSlot > -1) {
  11825. this._boundTexturesCache[currentSlot] = null;
  11826. this._nextFreeTextureSlots.push(currentSlot);
  11827. }
  11828. }
  11829. return currentSlot;
  11830. };
  11831. Engine.prototype._bindTextureDirectly = function (target, texture, doNotBindUniformToTextureChannel) {
  11832. if (doNotBindUniformToTextureChannel === void 0) { doNotBindUniformToTextureChannel = false; }
  11833. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  11834. var isTextureForRendering = texture && texture._initialSlot > -1;
  11835. if (currentTextureBound !== texture) {
  11836. if (currentTextureBound) {
  11837. this._removeDesignatedSlot(currentTextureBound);
  11838. }
  11839. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  11840. if (this._activeChannel >= 0) {
  11841. this._boundTexturesCache[this._activeChannel] = texture;
  11842. if (isTextureForRendering) {
  11843. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  11844. if (slotIndex > -1) {
  11845. this._nextFreeTextureSlots.splice(slotIndex, 1);
  11846. }
  11847. this._boundTexturesStack.push(texture);
  11848. }
  11849. }
  11850. }
  11851. if (isTextureForRendering && this._activeChannel > -1) {
  11852. texture._designatedSlot = this._activeChannel;
  11853. if (!doNotBindUniformToTextureChannel) {
  11854. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  11855. }
  11856. }
  11857. };
  11858. Engine.prototype._bindTexture = function (channel, texture) {
  11859. if (channel < 0) {
  11860. return;
  11861. }
  11862. if (texture) {
  11863. channel = this._getCorrectTextureChannel(channel, texture);
  11864. }
  11865. this._activateTextureChannel(channel);
  11866. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  11867. };
  11868. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  11869. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  11870. };
  11871. Engine.prototype.unbindAllTextures = function () {
  11872. for (var channel = 0; channel < this._caps.maxCombinedTexturesImageUnits; channel++) {
  11873. this._activateTextureChannel(channel);
  11874. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11875. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11876. if (this.webGLVersion > 1) {
  11877. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11878. }
  11879. }
  11880. };
  11881. Engine.prototype.setTexture = function (channel, uniform, texture) {
  11882. if (channel < 0) {
  11883. return;
  11884. }
  11885. if (uniform) {
  11886. this._boundUniforms[channel] = uniform;
  11887. }
  11888. this._setTexture(channel, texture);
  11889. };
  11890. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  11891. if (!internalTexture) {
  11892. return -1;
  11893. }
  11894. internalTexture._initialSlot = channel;
  11895. if (channel !== internalTexture._designatedSlot) {
  11896. if (internalTexture._designatedSlot > -1) {
  11897. return internalTexture._designatedSlot;
  11898. }
  11899. else {
  11900. // No slot for this texture, let's pick a new one (if we find a free slot)
  11901. if (this._nextFreeTextureSlots.length) {
  11902. return this._nextFreeTextureSlots[0];
  11903. }
  11904. // We need to recycle the oldest bound texture, sorry.
  11905. this._textureCollisions.addCount(1, false);
  11906. return this._removeDesignatedSlot(this._boundTexturesStack[0]);
  11907. }
  11908. }
  11909. return channel;
  11910. };
  11911. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  11912. var uniform = this._boundUniforms[sourceSlot];
  11913. this._gl.uniform1i(uniform, destination);
  11914. };
  11915. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  11916. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  11917. // Not ready?
  11918. if (!texture) {
  11919. if (this._boundTexturesCache[channel] != null) {
  11920. this._activateTextureChannel(channel);
  11921. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11922. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11923. if (this.webGLVersion > 1) {
  11924. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11925. }
  11926. }
  11927. return false;
  11928. }
  11929. // Video
  11930. var alreadyActivated = false;
  11931. if (texture.video) {
  11932. this._activateTextureChannel(channel);
  11933. alreadyActivated = true;
  11934. texture.update();
  11935. }
  11936. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  11937. texture.delayLoad();
  11938. return false;
  11939. }
  11940. var internalTexture;
  11941. if (texture.isReady()) {
  11942. internalTexture = texture.getInternalTexture();
  11943. }
  11944. else if (texture.isCube) {
  11945. internalTexture = this.emptyCubeTexture;
  11946. }
  11947. else if (texture.is3D) {
  11948. internalTexture = this.emptyTexture3D;
  11949. }
  11950. else {
  11951. internalTexture = this.emptyTexture;
  11952. }
  11953. if (!isPartOfTextureArray) {
  11954. channel = this._getCorrectTextureChannel(channel, internalTexture);
  11955. }
  11956. if (this._boundTexturesCache[channel] === internalTexture) {
  11957. this._moveBoundTextureOnTop(internalTexture);
  11958. if (!isPartOfTextureArray) {
  11959. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  11960. }
  11961. return false;
  11962. }
  11963. if (!alreadyActivated) {
  11964. this._activateTextureChannel(channel);
  11965. }
  11966. if (internalTexture && internalTexture.is3D) {
  11967. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  11968. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  11969. internalTexture._cachedWrapU = texture.wrapU;
  11970. switch (texture.wrapU) {
  11971. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11972. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11973. break;
  11974. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11975. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11976. break;
  11977. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11978. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11979. break;
  11980. }
  11981. }
  11982. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  11983. internalTexture._cachedWrapV = texture.wrapV;
  11984. switch (texture.wrapV) {
  11985. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11986. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11987. break;
  11988. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11989. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11990. break;
  11991. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11992. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11993. break;
  11994. }
  11995. }
  11996. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  11997. internalTexture._cachedWrapR = texture.wrapR;
  11998. switch (texture.wrapV) {
  11999. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12000. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  12001. break;
  12002. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12003. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  12004. break;
  12005. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12006. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  12007. break;
  12008. }
  12009. }
  12010. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  12011. }
  12012. else if (internalTexture && internalTexture.isCube) {
  12013. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  12014. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  12015. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  12016. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  12017. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  12018. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  12019. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  12020. }
  12021. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  12022. }
  12023. else {
  12024. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  12025. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  12026. internalTexture._cachedWrapU = texture.wrapU;
  12027. switch (texture.wrapU) {
  12028. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12029. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  12030. break;
  12031. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12032. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  12033. break;
  12034. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12035. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  12036. break;
  12037. }
  12038. }
  12039. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  12040. internalTexture._cachedWrapV = texture.wrapV;
  12041. switch (texture.wrapV) {
  12042. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12043. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  12044. break;
  12045. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12046. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  12047. break;
  12048. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12049. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  12050. break;
  12051. }
  12052. }
  12053. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  12054. }
  12055. return true;
  12056. };
  12057. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  12058. if (channel < 0 || !uniform) {
  12059. return;
  12060. }
  12061. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  12062. this._textureUnits = new Int32Array(textures.length);
  12063. }
  12064. for (var i = 0; i < textures.length; i++) {
  12065. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  12066. }
  12067. this._gl.uniform1iv(uniform, this._textureUnits);
  12068. for (var index = 0; index < textures.length; index++) {
  12069. this._setTexture(this._textureUnits[index], textures[index], true);
  12070. }
  12071. };
  12072. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  12073. var internalTexture = texture.getInternalTexture();
  12074. if (!internalTexture) {
  12075. return;
  12076. }
  12077. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  12078. var value = texture.anisotropicFilteringLevel;
  12079. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  12080. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  12081. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  12082. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  12083. }
  12084. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  12085. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  12086. internalTexture._cachedAnisotropicFilteringLevel = value;
  12087. }
  12088. };
  12089. Engine.prototype.readPixels = function (x, y, width, height) {
  12090. var data = new Uint8Array(height * width * 4);
  12091. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  12092. return data;
  12093. };
  12094. /**
  12095. * Add an externaly attached data from its key.
  12096. * This method call will fail and return false, if such key already exists.
  12097. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  12098. * @param key the unique key that identifies the data
  12099. * @param data the data object to associate to the key for this Engine instance
  12100. * @return true if no such key were already present and the data was added successfully, false otherwise
  12101. */
  12102. Engine.prototype.addExternalData = function (key, data) {
  12103. if (!this._externalData) {
  12104. this._externalData = new BABYLON.StringDictionary();
  12105. }
  12106. return this._externalData.add(key, data);
  12107. };
  12108. /**
  12109. * Get an externaly attached data from its key
  12110. * @param key the unique key that identifies the data
  12111. * @return the associated data, if present (can be null), or undefined if not present
  12112. */
  12113. Engine.prototype.getExternalData = function (key) {
  12114. if (!this._externalData) {
  12115. this._externalData = new BABYLON.StringDictionary();
  12116. }
  12117. return this._externalData.get(key);
  12118. };
  12119. /**
  12120. * Get an externaly attached data from its key, create it using a factory if it's not already present
  12121. * @param key the unique key that identifies the data
  12122. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  12123. * @return the associated data, can be null if the factory returned null.
  12124. */
  12125. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  12126. if (!this._externalData) {
  12127. this._externalData = new BABYLON.StringDictionary();
  12128. }
  12129. return this._externalData.getOrAddWithFactory(key, factory);
  12130. };
  12131. /**
  12132. * Remove an externaly attached data from the Engine instance
  12133. * @param key the unique key that identifies the data
  12134. * @return true if the data was successfully removed, false if it doesn't exist
  12135. */
  12136. Engine.prototype.removeExternalData = function (key) {
  12137. if (!this._externalData) {
  12138. this._externalData = new BABYLON.StringDictionary();
  12139. }
  12140. return this._externalData.remove(key);
  12141. };
  12142. Engine.prototype.unbindAllAttributes = function () {
  12143. if (this._mustWipeVertexAttributes) {
  12144. this._mustWipeVertexAttributes = false;
  12145. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  12146. this._gl.disableVertexAttribArray(i);
  12147. this._vertexAttribArraysEnabled[i] = false;
  12148. this._currentBufferPointers[i].active = false;
  12149. }
  12150. return;
  12151. }
  12152. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  12153. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  12154. continue;
  12155. }
  12156. this._gl.disableVertexAttribArray(i);
  12157. this._vertexAttribArraysEnabled[i] = false;
  12158. this._currentBufferPointers[i].active = false;
  12159. }
  12160. };
  12161. Engine.prototype.releaseEffects = function () {
  12162. for (var name in this._compiledEffects) {
  12163. this._deleteProgram(this._compiledEffects[name]._program);
  12164. }
  12165. this._compiledEffects = {};
  12166. };
  12167. // Dispose
  12168. Engine.prototype.dispose = function () {
  12169. this.hideLoadingUI();
  12170. this.stopRenderLoop();
  12171. // Release postProcesses
  12172. while (this.postProcesses.length) {
  12173. this.postProcesses[0].dispose();
  12174. }
  12175. // Empty texture
  12176. if (this._emptyTexture) {
  12177. this._releaseTexture(this._emptyTexture);
  12178. this._emptyTexture = null;
  12179. }
  12180. if (this._emptyCubeTexture) {
  12181. this._releaseTexture(this._emptyCubeTexture);
  12182. this._emptyCubeTexture = null;
  12183. }
  12184. // Rescale PP
  12185. if (this._rescalePostProcess) {
  12186. this._rescalePostProcess.dispose();
  12187. }
  12188. // Release scenes
  12189. while (this.scenes.length) {
  12190. this.scenes[0].dispose();
  12191. }
  12192. // Release audio engine
  12193. if (Engine.audioEngine) {
  12194. Engine.audioEngine.dispose();
  12195. }
  12196. // Release effects
  12197. this.releaseEffects();
  12198. // Unbind
  12199. this.unbindAllAttributes();
  12200. if (this._dummyFramebuffer) {
  12201. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  12202. }
  12203. //WebVR
  12204. this.disableVR();
  12205. // Events
  12206. if (BABYLON.Tools.IsWindowObjectExist()) {
  12207. window.removeEventListener("blur", this._onBlur);
  12208. window.removeEventListener("focus", this._onFocus);
  12209. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  12210. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  12211. if (this._renderingCanvas) {
  12212. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  12213. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  12214. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  12215. if (!this._doNotHandleContextLost) {
  12216. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  12217. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  12218. }
  12219. }
  12220. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  12221. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  12222. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  12223. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  12224. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  12225. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  12226. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  12227. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  12228. if (this._onVrDisplayConnect) {
  12229. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12230. if (this._onVrDisplayDisconnect) {
  12231. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12232. }
  12233. if (this._onVrDisplayPresentChange) {
  12234. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12235. }
  12236. this._onVrDisplayConnect = null;
  12237. this._onVrDisplayDisconnect = null;
  12238. }
  12239. }
  12240. // Remove from Instances
  12241. var index = Engine.Instances.indexOf(this);
  12242. if (index >= 0) {
  12243. Engine.Instances.splice(index, 1);
  12244. }
  12245. this._workingCanvas = null;
  12246. this._workingContext = null;
  12247. this._currentBufferPointers = [];
  12248. this._renderingCanvas = null;
  12249. this._currentProgram = null;
  12250. this.onResizeObservable.clear();
  12251. this.onCanvasBlurObservable.clear();
  12252. this.onCanvasFocusObservable.clear();
  12253. this.onCanvasPointerOutObservable.clear();
  12254. this.onBeginFrameObservable.clear();
  12255. this.onEndFrameObservable.clear();
  12256. BABYLON.Effect.ResetCache();
  12257. // Abort active requests
  12258. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  12259. var request = _a[_i];
  12260. request.abort();
  12261. }
  12262. };
  12263. // Loading screen
  12264. Engine.prototype.displayLoadingUI = function () {
  12265. if (!BABYLON.Tools.IsWindowObjectExist()) {
  12266. return;
  12267. }
  12268. var loadingScreen = this.loadingScreen;
  12269. if (loadingScreen) {
  12270. loadingScreen.displayLoadingUI();
  12271. }
  12272. };
  12273. Engine.prototype.hideLoadingUI = function () {
  12274. if (!BABYLON.Tools.IsWindowObjectExist()) {
  12275. return;
  12276. }
  12277. var loadingScreen = this.loadingScreen;
  12278. if (loadingScreen) {
  12279. loadingScreen.hideLoadingUI();
  12280. }
  12281. };
  12282. Object.defineProperty(Engine.prototype, "loadingScreen", {
  12283. get: function () {
  12284. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  12285. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  12286. return this._loadingScreen;
  12287. },
  12288. set: function (loadingScreen) {
  12289. this._loadingScreen = loadingScreen;
  12290. },
  12291. enumerable: true,
  12292. configurable: true
  12293. });
  12294. Object.defineProperty(Engine.prototype, "loadingUIText", {
  12295. set: function (text) {
  12296. this.loadingScreen.loadingUIText = text;
  12297. },
  12298. enumerable: true,
  12299. configurable: true
  12300. });
  12301. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  12302. set: function (color) {
  12303. this.loadingScreen.loadingUIBackgroundColor = color;
  12304. },
  12305. enumerable: true,
  12306. configurable: true
  12307. });
  12308. Engine.prototype.attachContextLostEvent = function (callback) {
  12309. if (this._renderingCanvas) {
  12310. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  12311. }
  12312. };
  12313. Engine.prototype.attachContextRestoredEvent = function (callback) {
  12314. if (this._renderingCanvas) {
  12315. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  12316. }
  12317. };
  12318. Engine.prototype.getVertexShaderSource = function (program) {
  12319. var shaders = this._gl.getAttachedShaders(program);
  12320. if (!shaders) {
  12321. return null;
  12322. }
  12323. return this._gl.getShaderSource(shaders[0]);
  12324. };
  12325. Engine.prototype.getFragmentShaderSource = function (program) {
  12326. var shaders = this._gl.getAttachedShaders(program);
  12327. if (!shaders) {
  12328. return null;
  12329. }
  12330. return this._gl.getShaderSource(shaders[1]);
  12331. };
  12332. Engine.prototype.getError = function () {
  12333. return this._gl.getError();
  12334. };
  12335. // FPS
  12336. Engine.prototype.getFps = function () {
  12337. return this._fps;
  12338. };
  12339. Engine.prototype.getDeltaTime = function () {
  12340. return this._deltaTime;
  12341. };
  12342. Engine.prototype._measureFps = function () {
  12343. this._performanceMonitor.sampleFrame();
  12344. this._fps = this._performanceMonitor.averageFPS;
  12345. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  12346. };
  12347. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  12348. if (faceIndex === void 0) { faceIndex = -1; }
  12349. var gl = this._gl;
  12350. if (!this._dummyFramebuffer) {
  12351. var dummy = gl.createFramebuffer();
  12352. if (!dummy) {
  12353. throw new Error("Unable to create dummy framebuffer");
  12354. }
  12355. this._dummyFramebuffer = dummy;
  12356. }
  12357. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  12358. if (faceIndex > -1) {
  12359. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  12360. }
  12361. else {
  12362. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  12363. }
  12364. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  12365. var buffer;
  12366. switch (readType) {
  12367. case gl.UNSIGNED_BYTE:
  12368. buffer = new Uint8Array(4 * width * height);
  12369. readType = gl.UNSIGNED_BYTE;
  12370. break;
  12371. default:
  12372. buffer = new Float32Array(4 * width * height);
  12373. readType = gl.FLOAT;
  12374. break;
  12375. }
  12376. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  12377. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  12378. return buffer;
  12379. };
  12380. Engine.prototype._canRenderToFloatFramebuffer = function () {
  12381. if (this._webGLVersion > 1) {
  12382. return this._caps.colorBufferFloat;
  12383. }
  12384. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  12385. };
  12386. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  12387. if (this._webGLVersion > 1) {
  12388. return this._caps.colorBufferFloat;
  12389. }
  12390. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  12391. };
  12392. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  12393. Engine.prototype._canRenderToFramebuffer = function (type) {
  12394. var gl = this._gl;
  12395. //clear existing errors
  12396. while (gl.getError() !== gl.NO_ERROR) { }
  12397. var successful = true;
  12398. var texture = gl.createTexture();
  12399. gl.bindTexture(gl.TEXTURE_2D, texture);
  12400. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  12401. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12402. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12403. var fb = gl.createFramebuffer();
  12404. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  12405. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  12406. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  12407. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  12408. successful = successful && (gl.getError() === gl.NO_ERROR);
  12409. //try render by clearing frame buffer's color buffer
  12410. if (successful) {
  12411. gl.clear(gl.COLOR_BUFFER_BIT);
  12412. successful = successful && (gl.getError() === gl.NO_ERROR);
  12413. }
  12414. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  12415. if (successful) {
  12416. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  12417. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  12418. var readFormat = gl.RGBA;
  12419. var readType = gl.UNSIGNED_BYTE;
  12420. var buffer = new Uint8Array(4);
  12421. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  12422. successful = successful && (gl.getError() === gl.NO_ERROR);
  12423. }
  12424. //clean up
  12425. gl.deleteTexture(texture);
  12426. gl.deleteFramebuffer(fb);
  12427. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  12428. //clear accumulated errors
  12429. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  12430. return successful;
  12431. };
  12432. Engine.prototype._getWebGLTextureType = function (type) {
  12433. if (type === Engine.TEXTURETYPE_FLOAT) {
  12434. return this._gl.FLOAT;
  12435. }
  12436. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  12437. // Add Half Float Constant.
  12438. return this._gl.HALF_FLOAT_OES;
  12439. }
  12440. return this._gl.UNSIGNED_BYTE;
  12441. };
  12442. ;
  12443. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  12444. if (this._webGLVersion === 1) {
  12445. return this._gl.RGBA;
  12446. }
  12447. if (type === Engine.TEXTURETYPE_FLOAT) {
  12448. return this._gl.RGBA32F;
  12449. }
  12450. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  12451. return this._gl.RGBA16F;
  12452. }
  12453. return this._gl.RGBA;
  12454. };
  12455. ;
  12456. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  12457. if (type === Engine.TEXTURETYPE_FLOAT) {
  12458. return this._gl.RGBA32F;
  12459. }
  12460. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  12461. return this._gl.RGBA16F;
  12462. }
  12463. return this._gl.RGBA8;
  12464. };
  12465. ;
  12466. Engine.prototype.createQuery = function () {
  12467. return this._gl.createQuery();
  12468. };
  12469. Engine.prototype.deleteQuery = function (query) {
  12470. this._gl.deleteQuery(query);
  12471. return this;
  12472. };
  12473. Engine.prototype.isQueryResultAvailable = function (query) {
  12474. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  12475. };
  12476. Engine.prototype.getQueryResult = function (query) {
  12477. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  12478. };
  12479. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  12480. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  12481. this._gl.beginQuery(glAlgorithm, query);
  12482. return this;
  12483. };
  12484. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  12485. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  12486. this._gl.endQuery(glAlgorithm);
  12487. return this;
  12488. };
  12489. /* Time queries */
  12490. Engine.prototype._createTimeQuery = function () {
  12491. var timerQuery = this._caps.timerQuery;
  12492. if (timerQuery.createQueryEXT) {
  12493. return timerQuery.createQueryEXT();
  12494. }
  12495. return this.createQuery();
  12496. };
  12497. Engine.prototype._deleteTimeQuery = function (query) {
  12498. var timerQuery = this._caps.timerQuery;
  12499. if (timerQuery.deleteQueryEXT) {
  12500. timerQuery.deleteQueryEXT(query);
  12501. return;
  12502. }
  12503. this.deleteQuery(query);
  12504. };
  12505. Engine.prototype._getTimeQueryResult = function (query) {
  12506. var timerQuery = this._caps.timerQuery;
  12507. if (timerQuery.getQueryObjectEXT) {
  12508. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  12509. }
  12510. return this.getQueryResult(query);
  12511. };
  12512. Engine.prototype._getTimeQueryAvailability = function (query) {
  12513. var timerQuery = this._caps.timerQuery;
  12514. if (timerQuery.getQueryObjectEXT) {
  12515. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  12516. }
  12517. return this.isQueryResultAvailable(query);
  12518. };
  12519. Engine.prototype.startTimeQuery = function () {
  12520. var timerQuery = this._caps.timerQuery;
  12521. if (!timerQuery) {
  12522. return null;
  12523. }
  12524. var token = new BABYLON._TimeToken();
  12525. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  12526. if (this._caps.canUseTimestampForTimerQuery) {
  12527. token._startTimeQuery = this._createTimeQuery();
  12528. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  12529. }
  12530. else {
  12531. if (this._currentNonTimestampToken) {
  12532. return this._currentNonTimestampToken;
  12533. }
  12534. token._timeElapsedQuery = this._createTimeQuery();
  12535. if (timerQuery.beginQueryEXT) {
  12536. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  12537. }
  12538. else {
  12539. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  12540. }
  12541. this._currentNonTimestampToken = token;
  12542. }
  12543. return token;
  12544. };
  12545. Engine.prototype.endTimeQuery = function (token) {
  12546. var timerQuery = this._caps.timerQuery;
  12547. if (!timerQuery || !token) {
  12548. return -1;
  12549. }
  12550. if (this._caps.canUseTimestampForTimerQuery) {
  12551. if (!token._startTimeQuery) {
  12552. return -1;
  12553. }
  12554. if (!token._endTimeQuery) {
  12555. token._endTimeQuery = this._createTimeQuery();
  12556. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  12557. }
  12558. }
  12559. else if (!token._timeElapsedQueryEnded) {
  12560. if (!token._timeElapsedQuery) {
  12561. return -1;
  12562. }
  12563. if (timerQuery.endQueryEXT) {
  12564. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  12565. }
  12566. else {
  12567. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  12568. }
  12569. token._timeElapsedQueryEnded = true;
  12570. }
  12571. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  12572. var available = false;
  12573. if (token._endTimeQuery) {
  12574. available = this._getTimeQueryAvailability(token._endTimeQuery);
  12575. }
  12576. else if (token._timeElapsedQuery) {
  12577. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  12578. }
  12579. if (available && !disjoint) {
  12580. var result = 0;
  12581. if (this._caps.canUseTimestampForTimerQuery) {
  12582. if (!token._startTimeQuery || !token._endTimeQuery) {
  12583. return -1;
  12584. }
  12585. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  12586. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  12587. result = timeEnd - timeStart;
  12588. this._deleteTimeQuery(token._startTimeQuery);
  12589. this._deleteTimeQuery(token._endTimeQuery);
  12590. token._startTimeQuery = null;
  12591. token._endTimeQuery = null;
  12592. }
  12593. else {
  12594. if (!token._timeElapsedQuery) {
  12595. return -1;
  12596. }
  12597. result = this._getTimeQueryResult(token._timeElapsedQuery);
  12598. this._deleteTimeQuery(token._timeElapsedQuery);
  12599. token._timeElapsedQuery = null;
  12600. token._timeElapsedQueryEnded = false;
  12601. this._currentNonTimestampToken = null;
  12602. }
  12603. return result;
  12604. }
  12605. return -1;
  12606. };
  12607. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  12608. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  12609. };
  12610. // Transform feedback
  12611. Engine.prototype.createTransformFeedback = function () {
  12612. return this._gl.createTransformFeedback();
  12613. };
  12614. Engine.prototype.deleteTransformFeedback = function (value) {
  12615. this._gl.deleteTransformFeedback(value);
  12616. };
  12617. Engine.prototype.bindTransformFeedback = function (value) {
  12618. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  12619. };
  12620. Engine.prototype.beginTransformFeedback = function (usePoints) {
  12621. if (usePoints === void 0) { usePoints = true; }
  12622. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  12623. };
  12624. Engine.prototype.endTransformFeedback = function () {
  12625. this._gl.endTransformFeedback();
  12626. };
  12627. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  12628. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  12629. };
  12630. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  12631. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  12632. };
  12633. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  12634. var _this = this;
  12635. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  12636. this._activeRequests.push(request);
  12637. request.onCompleteObservable.add(function (request) {
  12638. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  12639. });
  12640. return request;
  12641. };
  12642. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  12643. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  12644. var onload = function (data) {
  12645. loadedFiles[index] = data;
  12646. loadedFiles._internalCount++;
  12647. if (loadedFiles._internalCount === 6) {
  12648. onfinish(loadedFiles);
  12649. }
  12650. };
  12651. var onerror = function (request, exception) {
  12652. if (onErrorCallBack && request) {
  12653. onErrorCallBack(request.status + " " + request.statusText, exception);
  12654. }
  12655. };
  12656. this._loadFile(url, onload, undefined, undefined, true, onerror);
  12657. };
  12658. Engine.prototype._cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  12659. if (onError === void 0) { onError = null; }
  12660. var loadedFiles = [];
  12661. loadedFiles._internalCount = 0;
  12662. for (var index = 0; index < 6; index++) {
  12663. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  12664. }
  12665. };
  12666. // Statics
  12667. Engine.isSupported = function () {
  12668. try {
  12669. var tempcanvas = document.createElement("canvas");
  12670. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  12671. return gl != null && !!window.WebGLRenderingContext;
  12672. }
  12673. catch (e) {
  12674. return false;
  12675. }
  12676. };
  12677. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  12678. Engine.ExceptionList = [
  12679. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  12680. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] }
  12681. ];
  12682. Engine.Instances = new Array();
  12683. // Const statics
  12684. Engine._ALPHA_DISABLE = 0;
  12685. Engine._ALPHA_ADD = 1;
  12686. Engine._ALPHA_COMBINE = 2;
  12687. Engine._ALPHA_SUBTRACT = 3;
  12688. Engine._ALPHA_MULTIPLY = 4;
  12689. Engine._ALPHA_MAXIMIZED = 5;
  12690. Engine._ALPHA_ONEONE = 6;
  12691. Engine._ALPHA_PREMULTIPLIED = 7;
  12692. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  12693. Engine._ALPHA_INTERPOLATE = 9;
  12694. Engine._ALPHA_SCREENMODE = 10;
  12695. Engine._DELAYLOADSTATE_NONE = 0;
  12696. Engine._DELAYLOADSTATE_LOADED = 1;
  12697. Engine._DELAYLOADSTATE_LOADING = 2;
  12698. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  12699. Engine._TEXTUREFORMAT_ALPHA = 0;
  12700. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  12701. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  12702. Engine._TEXTUREFORMAT_RGB = 4;
  12703. Engine._TEXTUREFORMAT_RGBA = 5;
  12704. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  12705. Engine._TEXTURETYPE_FLOAT = 1;
  12706. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  12707. // Depht or Stencil test Constants.
  12708. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  12709. 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.
  12710. 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.
  12711. 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.
  12712. 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.
  12713. 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.
  12714. 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.
  12715. 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.
  12716. // Stencil Actions Constants.
  12717. Engine._KEEP = 0x1E00;
  12718. Engine._REPLACE = 0x1E01;
  12719. Engine._INCR = 0x1E02;
  12720. Engine._DECR = 0x1E03;
  12721. Engine._INVERT = 0x150A;
  12722. Engine._INCR_WRAP = 0x8507;
  12723. Engine._DECR_WRAP = 0x8508;
  12724. // Texture rescaling mode
  12725. Engine._SCALEMODE_FLOOR = 1;
  12726. Engine._SCALEMODE_NEAREST = 2;
  12727. Engine._SCALEMODE_CEILING = 3;
  12728. // Updatable statics so stick with vars here
  12729. Engine.CollisionsEpsilon = 0.001;
  12730. Engine.CodeRepository = "src/";
  12731. Engine.ShadersRepository = "src/Shaders/";
  12732. return Engine;
  12733. }());
  12734. BABYLON.Engine = Engine;
  12735. })(BABYLON || (BABYLON = {}));
  12736. //# sourceMappingURL=babylon.engine.js.map
  12737. var BABYLON;
  12738. (function (BABYLON) {
  12739. /**
  12740. * Node is the basic class for all scene objects (Mesh, Light Camera).
  12741. */
  12742. var Node = /** @class */ (function () {
  12743. /**
  12744. * @constructor
  12745. * @param {string} name - the name and id to be given to this node
  12746. * @param {BABYLON.Scene} the scene this node will be added to
  12747. */
  12748. function Node(name, scene) {
  12749. if (scene === void 0) { scene = null; }
  12750. this.state = "";
  12751. this.metadata = null;
  12752. this.doNotSerialize = false;
  12753. this.animations = new Array();
  12754. this._ranges = {};
  12755. this._isEnabled = true;
  12756. this._isReady = true;
  12757. this._currentRenderId = -1;
  12758. this._parentRenderId = -1;
  12759. /**
  12760. * An event triggered when the mesh is disposed.
  12761. * @type {BABYLON.Observable}
  12762. */
  12763. this.onDisposeObservable = new BABYLON.Observable();
  12764. // Behaviors
  12765. this._behaviors = new Array();
  12766. this.name = name;
  12767. this.id = name;
  12768. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  12769. this.uniqueId = this._scene.getUniqueId();
  12770. this._initCache();
  12771. }
  12772. Object.defineProperty(Node.prototype, "parent", {
  12773. get: function () {
  12774. return this._parentNode;
  12775. },
  12776. set: function (parent) {
  12777. if (this._parentNode === parent) {
  12778. return;
  12779. }
  12780. // Remove self from list of children of parent
  12781. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  12782. var index = this._parentNode._children.indexOf(this);
  12783. if (index !== -1) {
  12784. this._parentNode._children.splice(index, 1);
  12785. }
  12786. }
  12787. // Store new parent
  12788. this._parentNode = parent;
  12789. // Add as child to new parent
  12790. if (this._parentNode) {
  12791. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  12792. this._parentNode._children = new Array();
  12793. }
  12794. this._parentNode._children.push(this);
  12795. }
  12796. },
  12797. enumerable: true,
  12798. configurable: true
  12799. });
  12800. Node.prototype.getClassName = function () {
  12801. return "Node";
  12802. };
  12803. Object.defineProperty(Node.prototype, "onDispose", {
  12804. set: function (callback) {
  12805. if (this._onDisposeObserver) {
  12806. this.onDisposeObservable.remove(this._onDisposeObserver);
  12807. }
  12808. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  12809. },
  12810. enumerable: true,
  12811. configurable: true
  12812. });
  12813. Node.prototype.getScene = function () {
  12814. return this._scene;
  12815. };
  12816. Node.prototype.getEngine = function () {
  12817. return this._scene.getEngine();
  12818. };
  12819. Node.prototype.addBehavior = function (behavior) {
  12820. var _this = this;
  12821. var index = this._behaviors.indexOf(behavior);
  12822. if (index !== -1) {
  12823. return this;
  12824. }
  12825. behavior.init();
  12826. if (this._scene.isLoading) {
  12827. // We defer the attach when the scene will be loaded
  12828. var observer = this._scene.onDataLoadedObservable.add(function () {
  12829. behavior.attach(_this);
  12830. setTimeout(function () {
  12831. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  12832. _this._scene.onDataLoadedObservable.remove(observer);
  12833. }, 0);
  12834. });
  12835. }
  12836. else {
  12837. behavior.attach(this);
  12838. }
  12839. this._behaviors.push(behavior);
  12840. return this;
  12841. };
  12842. Node.prototype.removeBehavior = function (behavior) {
  12843. var index = this._behaviors.indexOf(behavior);
  12844. if (index === -1) {
  12845. return this;
  12846. }
  12847. this._behaviors[index].detach();
  12848. this._behaviors.splice(index, 1);
  12849. return this;
  12850. };
  12851. Object.defineProperty(Node.prototype, "behaviors", {
  12852. get: function () {
  12853. return this._behaviors;
  12854. },
  12855. enumerable: true,
  12856. configurable: true
  12857. });
  12858. Node.prototype.getBehaviorByName = function (name) {
  12859. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  12860. var behavior = _a[_i];
  12861. if (behavior.name === name) {
  12862. return behavior;
  12863. }
  12864. }
  12865. return null;
  12866. };
  12867. // override it in derived class
  12868. Node.prototype.getWorldMatrix = function () {
  12869. return BABYLON.Matrix.Identity();
  12870. };
  12871. // override it in derived class if you add new variables to the cache
  12872. // and call the parent class method
  12873. Node.prototype._initCache = function () {
  12874. this._cache = {};
  12875. this._cache.parent = undefined;
  12876. };
  12877. Node.prototype.updateCache = function (force) {
  12878. if (!force && this.isSynchronized())
  12879. return;
  12880. this._cache.parent = this.parent;
  12881. this._updateCache();
  12882. };
  12883. // override it in derived class if you add new variables to the cache
  12884. // and call the parent class method if !ignoreParentClass
  12885. Node.prototype._updateCache = function (ignoreParentClass) {
  12886. };
  12887. // override it in derived class if you add new variables to the cache
  12888. Node.prototype._isSynchronized = function () {
  12889. return true;
  12890. };
  12891. Node.prototype._markSyncedWithParent = function () {
  12892. if (this.parent) {
  12893. this._parentRenderId = this.parent._currentRenderId;
  12894. }
  12895. };
  12896. Node.prototype.isSynchronizedWithParent = function () {
  12897. if (!this.parent) {
  12898. return true;
  12899. }
  12900. if (this._parentRenderId !== this.parent._currentRenderId) {
  12901. return false;
  12902. }
  12903. return this.parent.isSynchronized();
  12904. };
  12905. Node.prototype.isSynchronized = function (updateCache) {
  12906. var check = this.hasNewParent();
  12907. check = check || !this.isSynchronizedWithParent();
  12908. check = check || !this._isSynchronized();
  12909. if (updateCache)
  12910. this.updateCache(true);
  12911. return !check;
  12912. };
  12913. Node.prototype.hasNewParent = function (update) {
  12914. if (this._cache.parent === this.parent)
  12915. return false;
  12916. if (update)
  12917. this._cache.parent = this.parent;
  12918. return true;
  12919. };
  12920. /**
  12921. * Is this node ready to be used/rendered
  12922. * @return {boolean} is it ready
  12923. */
  12924. Node.prototype.isReady = function () {
  12925. return this._isReady;
  12926. };
  12927. /**
  12928. * Is this node enabled.
  12929. * 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.
  12930. * @param {boolean} [checkAncestors=true] - 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.
  12931. * @return {boolean} whether this node (and its parent) is enabled.
  12932. * @see setEnabled
  12933. */
  12934. Node.prototype.isEnabled = function (checkAncestors) {
  12935. if (checkAncestors === void 0) { checkAncestors = true; }
  12936. if (checkAncestors === false) {
  12937. return this._isEnabled;
  12938. }
  12939. if (this._isEnabled === false) {
  12940. return false;
  12941. }
  12942. if (this.parent !== undefined && this.parent !== null) {
  12943. return this.parent.isEnabled(checkAncestors);
  12944. }
  12945. return true;
  12946. };
  12947. /**
  12948. * Set the enabled state of this node.
  12949. * @param {boolean} value - the new enabled state
  12950. * @see isEnabled
  12951. */
  12952. Node.prototype.setEnabled = function (value) {
  12953. this._isEnabled = value;
  12954. };
  12955. /**
  12956. * Is this node a descendant of the given node.
  12957. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  12958. * @param {BABYLON.Node} ancestor - The parent node to inspect
  12959. * @see parent
  12960. */
  12961. Node.prototype.isDescendantOf = function (ancestor) {
  12962. if (this.parent) {
  12963. if (this.parent === ancestor) {
  12964. return true;
  12965. }
  12966. return this.parent.isDescendantOf(ancestor);
  12967. }
  12968. return false;
  12969. };
  12970. /**
  12971. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  12972. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  12973. * @param {boolean} directDescendantsOnly 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.
  12974. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  12975. */
  12976. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  12977. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  12978. if (!this._children) {
  12979. return;
  12980. }
  12981. for (var index = 0; index < this._children.length; index++) {
  12982. var item = this._children[index];
  12983. if (!predicate || predicate(item)) {
  12984. results.push(item);
  12985. }
  12986. if (!directDescendantsOnly) {
  12987. item._getDescendants(results, false, predicate);
  12988. }
  12989. }
  12990. };
  12991. /**
  12992. * Will return all nodes that have this node as ascendant.
  12993. * @param {boolean} directDescendantsOnly 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.
  12994. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  12995. * @return {BABYLON.Node[]} all children nodes of all types.
  12996. */
  12997. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  12998. var results = new Array();
  12999. this._getDescendants(results, directDescendantsOnly, predicate);
  13000. return results;
  13001. };
  13002. /**
  13003. * Get all child-meshes of this node.
  13004. */
  13005. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  13006. var results = [];
  13007. this._getDescendants(results, directDescendantsOnly, function (node) {
  13008. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  13009. });
  13010. return results;
  13011. };
  13012. /**
  13013. * Get all child-transformNodes of this node.
  13014. */
  13015. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  13016. var results = [];
  13017. this._getDescendants(results, directDescendantsOnly, function (node) {
  13018. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  13019. });
  13020. return results;
  13021. };
  13022. /**
  13023. * Get all direct children of this node.
  13024. */
  13025. Node.prototype.getChildren = function (predicate) {
  13026. return this.getDescendants(true, predicate);
  13027. };
  13028. Node.prototype._setReady = function (state) {
  13029. if (state === this._isReady) {
  13030. return;
  13031. }
  13032. if (!state) {
  13033. this._isReady = false;
  13034. return;
  13035. }
  13036. this._isReady = true;
  13037. if (this.onReady) {
  13038. this.onReady(this);
  13039. }
  13040. };
  13041. Node.prototype.getAnimationByName = function (name) {
  13042. for (var i = 0; i < this.animations.length; i++) {
  13043. var animation = this.animations[i];
  13044. if (animation.name === name) {
  13045. return animation;
  13046. }
  13047. }
  13048. return null;
  13049. };
  13050. Node.prototype.createAnimationRange = function (name, from, to) {
  13051. // check name not already in use
  13052. if (!this._ranges[name]) {
  13053. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  13054. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  13055. if (this.animations[i]) {
  13056. this.animations[i].createRange(name, from, to);
  13057. }
  13058. }
  13059. }
  13060. };
  13061. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  13062. if (deleteFrames === void 0) { deleteFrames = true; }
  13063. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  13064. if (this.animations[i]) {
  13065. this.animations[i].deleteRange(name, deleteFrames);
  13066. }
  13067. }
  13068. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  13069. };
  13070. Node.prototype.getAnimationRange = function (name) {
  13071. return this._ranges[name];
  13072. };
  13073. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  13074. var range = this.getAnimationRange(name);
  13075. if (!range) {
  13076. return;
  13077. }
  13078. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  13079. };
  13080. Node.prototype.serializeAnimationRanges = function () {
  13081. var serializationRanges = [];
  13082. for (var name in this._ranges) {
  13083. var localRange = this._ranges[name];
  13084. if (!localRange) {
  13085. continue;
  13086. }
  13087. var range = {};
  13088. range.name = name;
  13089. range.from = localRange.from;
  13090. range.to = localRange.to;
  13091. serializationRanges.push(range);
  13092. }
  13093. return serializationRanges;
  13094. };
  13095. // override it in derived class
  13096. Node.prototype.computeWorldMatrix = function (force) {
  13097. return BABYLON.Matrix.Identity();
  13098. };
  13099. Node.prototype.dispose = function () {
  13100. this.parent = null;
  13101. // Callback
  13102. this.onDisposeObservable.notifyObservers(this);
  13103. this.onDisposeObservable.clear();
  13104. // Behaviors
  13105. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  13106. var behavior = _a[_i];
  13107. behavior.detach();
  13108. }
  13109. this._behaviors = [];
  13110. };
  13111. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  13112. if (parsedNode.ranges) {
  13113. for (var index = 0; index < parsedNode.ranges.length; index++) {
  13114. var data = parsedNode.ranges[index];
  13115. node.createAnimationRange(data.name, data.from, data.to);
  13116. }
  13117. }
  13118. };
  13119. __decorate([
  13120. BABYLON.serialize()
  13121. ], Node.prototype, "name", void 0);
  13122. __decorate([
  13123. BABYLON.serialize()
  13124. ], Node.prototype, "id", void 0);
  13125. __decorate([
  13126. BABYLON.serialize()
  13127. ], Node.prototype, "uniqueId", void 0);
  13128. __decorate([
  13129. BABYLON.serialize()
  13130. ], Node.prototype, "state", void 0);
  13131. __decorate([
  13132. BABYLON.serialize()
  13133. ], Node.prototype, "metadata", void 0);
  13134. return Node;
  13135. }());
  13136. BABYLON.Node = Node;
  13137. })(BABYLON || (BABYLON = {}));
  13138. //# sourceMappingURL=babylon.node.js.map
  13139. var BABYLON;
  13140. (function (BABYLON) {
  13141. var BoundingSphere = /** @class */ (function () {
  13142. function BoundingSphere(minimum, maximum) {
  13143. this.minimum = minimum;
  13144. this.maximum = maximum;
  13145. this._tempRadiusVector = BABYLON.Vector3.Zero();
  13146. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  13147. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  13148. this.radius = distance * 0.5;
  13149. this.centerWorld = BABYLON.Vector3.Zero();
  13150. this._update(BABYLON.Matrix.Identity());
  13151. }
  13152. // Methods
  13153. BoundingSphere.prototype._update = function (world) {
  13154. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  13155. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  13156. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  13157. };
  13158. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  13159. for (var i = 0; i < 6; i++) {
  13160. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  13161. return false;
  13162. }
  13163. return true;
  13164. };
  13165. BoundingSphere.prototype.intersectsPoint = function (point) {
  13166. var x = this.centerWorld.x - point.x;
  13167. var y = this.centerWorld.y - point.y;
  13168. var z = this.centerWorld.z - point.z;
  13169. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  13170. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  13171. return false;
  13172. return true;
  13173. };
  13174. // Statics
  13175. BoundingSphere.Intersects = function (sphere0, sphere1) {
  13176. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  13177. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  13178. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  13179. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  13180. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  13181. return false;
  13182. return true;
  13183. };
  13184. return BoundingSphere;
  13185. }());
  13186. BABYLON.BoundingSphere = BoundingSphere;
  13187. })(BABYLON || (BABYLON = {}));
  13188. //# sourceMappingURL=babylon.boundingSphere.js.map
  13189. var BABYLON;
  13190. (function (BABYLON) {
  13191. var BoundingBox = /** @class */ (function () {
  13192. function BoundingBox(minimum, maximum) {
  13193. this.minimum = minimum;
  13194. this.maximum = maximum;
  13195. this.vectors = new Array();
  13196. this.vectorsWorld = new Array();
  13197. // Bounding vectors
  13198. this.vectors.push(this.minimum.clone());
  13199. this.vectors.push(this.maximum.clone());
  13200. this.vectors.push(this.minimum.clone());
  13201. this.vectors[2].x = this.maximum.x;
  13202. this.vectors.push(this.minimum.clone());
  13203. this.vectors[3].y = this.maximum.y;
  13204. this.vectors.push(this.minimum.clone());
  13205. this.vectors[4].z = this.maximum.z;
  13206. this.vectors.push(this.maximum.clone());
  13207. this.vectors[5].z = this.minimum.z;
  13208. this.vectors.push(this.maximum.clone());
  13209. this.vectors[6].x = this.minimum.x;
  13210. this.vectors.push(this.maximum.clone());
  13211. this.vectors[7].y = this.minimum.y;
  13212. // OBB
  13213. this.center = this.maximum.add(this.minimum).scale(0.5);
  13214. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  13215. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  13216. // World
  13217. for (var index = 0; index < this.vectors.length; index++) {
  13218. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  13219. }
  13220. this.minimumWorld = BABYLON.Vector3.Zero();
  13221. this.maximumWorld = BABYLON.Vector3.Zero();
  13222. this.centerWorld = BABYLON.Vector3.Zero();
  13223. this.extendSizeWorld = BABYLON.Vector3.Zero();
  13224. this._update(BABYLON.Matrix.Identity());
  13225. }
  13226. // Methods
  13227. BoundingBox.prototype.getWorldMatrix = function () {
  13228. return this._worldMatrix;
  13229. };
  13230. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  13231. this._worldMatrix.copyFrom(matrix);
  13232. return this;
  13233. };
  13234. BoundingBox.prototype._update = function (world) {
  13235. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  13236. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  13237. for (var index = 0; index < this.vectors.length; index++) {
  13238. var v = this.vectorsWorld[index];
  13239. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  13240. if (v.x < this.minimumWorld.x)
  13241. this.minimumWorld.x = v.x;
  13242. if (v.y < this.minimumWorld.y)
  13243. this.minimumWorld.y = v.y;
  13244. if (v.z < this.minimumWorld.z)
  13245. this.minimumWorld.z = v.z;
  13246. if (v.x > this.maximumWorld.x)
  13247. this.maximumWorld.x = v.x;
  13248. if (v.y > this.maximumWorld.y)
  13249. this.maximumWorld.y = v.y;
  13250. if (v.z > this.maximumWorld.z)
  13251. this.maximumWorld.z = v.z;
  13252. }
  13253. // Extend
  13254. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  13255. this.extendSizeWorld.scaleInPlace(0.5);
  13256. // OBB
  13257. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  13258. this.centerWorld.scaleInPlace(0.5);
  13259. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  13260. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  13261. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  13262. this._worldMatrix = world;
  13263. };
  13264. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  13265. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  13266. };
  13267. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  13268. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  13269. };
  13270. BoundingBox.prototype.intersectsPoint = function (point) {
  13271. var delta = -BABYLON.Epsilon;
  13272. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  13273. return false;
  13274. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  13275. return false;
  13276. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  13277. return false;
  13278. return true;
  13279. };
  13280. BoundingBox.prototype.intersectsSphere = function (sphere) {
  13281. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  13282. };
  13283. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  13284. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  13285. return false;
  13286. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  13287. return false;
  13288. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  13289. return false;
  13290. return true;
  13291. };
  13292. // Statics
  13293. BoundingBox.Intersects = function (box0, box1) {
  13294. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  13295. return false;
  13296. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  13297. return false;
  13298. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  13299. return false;
  13300. return true;
  13301. };
  13302. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  13303. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  13304. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  13305. return (num <= (sphereRadius * sphereRadius));
  13306. };
  13307. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  13308. for (var p = 0; p < 6; p++) {
  13309. for (var i = 0; i < 8; i++) {
  13310. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  13311. return false;
  13312. }
  13313. }
  13314. }
  13315. return true;
  13316. };
  13317. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  13318. for (var p = 0; p < 6; p++) {
  13319. var inCount = 8;
  13320. for (var i = 0; i < 8; i++) {
  13321. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  13322. --inCount;
  13323. }
  13324. else {
  13325. break;
  13326. }
  13327. }
  13328. if (inCount === 0)
  13329. return false;
  13330. }
  13331. return true;
  13332. };
  13333. return BoundingBox;
  13334. }());
  13335. BABYLON.BoundingBox = BoundingBox;
  13336. })(BABYLON || (BABYLON = {}));
  13337. //# sourceMappingURL=babylon.boundingBox.js.map
  13338. var BABYLON;
  13339. (function (BABYLON) {
  13340. var computeBoxExtents = function (axis, box) {
  13341. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  13342. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  13343. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  13344. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  13345. var r = r0 + r1 + r2;
  13346. return {
  13347. min: p - r,
  13348. max: p + r
  13349. };
  13350. };
  13351. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  13352. var axisOverlap = function (axis, box0, box1) {
  13353. var result0 = computeBoxExtents(axis, box0);
  13354. var result1 = computeBoxExtents(axis, box1);
  13355. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  13356. };
  13357. var BoundingInfo = /** @class */ (function () {
  13358. function BoundingInfo(minimum, maximum) {
  13359. this.minimum = minimum;
  13360. this.maximum = maximum;
  13361. this._isLocked = false;
  13362. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  13363. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  13364. }
  13365. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  13366. get: function () {
  13367. return this._isLocked;
  13368. },
  13369. set: function (value) {
  13370. this._isLocked = value;
  13371. },
  13372. enumerable: true,
  13373. configurable: true
  13374. });
  13375. // Methods
  13376. BoundingInfo.prototype.update = function (world) {
  13377. if (this._isLocked) {
  13378. return;
  13379. }
  13380. this.boundingBox._update(world);
  13381. this.boundingSphere._update(world);
  13382. };
  13383. /**
  13384. * Recreate the bounding info to be centered around a specific point given a specific extend.
  13385. * @param center New center of the bounding info
  13386. * @param extend New extend of the bounding info
  13387. */
  13388. BoundingInfo.prototype.centerOn = function (center, extend) {
  13389. this.minimum = center.subtract(extend);
  13390. this.maximum = center.add(extend);
  13391. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  13392. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  13393. return this;
  13394. };
  13395. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  13396. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  13397. return false;
  13398. return this.boundingBox.isInFrustum(frustumPlanes);
  13399. };
  13400. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  13401. /**
  13402. * Gets the world distance between the min and max points of the bounding box
  13403. */
  13404. get: function () {
  13405. var boundingBox = this.boundingBox;
  13406. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  13407. return size.length();
  13408. },
  13409. enumerable: true,
  13410. configurable: true
  13411. });
  13412. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  13413. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  13414. };
  13415. BoundingInfo.prototype._checkCollision = function (collider) {
  13416. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  13417. };
  13418. BoundingInfo.prototype.intersectsPoint = function (point) {
  13419. if (!this.boundingSphere.centerWorld) {
  13420. return false;
  13421. }
  13422. if (!this.boundingSphere.intersectsPoint(point)) {
  13423. return false;
  13424. }
  13425. if (!this.boundingBox.intersectsPoint(point)) {
  13426. return false;
  13427. }
  13428. return true;
  13429. };
  13430. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  13431. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  13432. return false;
  13433. }
  13434. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  13435. return false;
  13436. }
  13437. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  13438. return false;
  13439. }
  13440. if (!precise) {
  13441. return true;
  13442. }
  13443. var box0 = this.boundingBox;
  13444. var box1 = boundingInfo.boundingBox;
  13445. if (!axisOverlap(box0.directions[0], box0, box1))
  13446. return false;
  13447. if (!axisOverlap(box0.directions[1], box0, box1))
  13448. return false;
  13449. if (!axisOverlap(box0.directions[2], box0, box1))
  13450. return false;
  13451. if (!axisOverlap(box1.directions[0], box0, box1))
  13452. return false;
  13453. if (!axisOverlap(box1.directions[1], box0, box1))
  13454. return false;
  13455. if (!axisOverlap(box1.directions[2], box0, box1))
  13456. return false;
  13457. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  13458. return false;
  13459. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  13460. return false;
  13461. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  13462. return false;
  13463. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  13464. return false;
  13465. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  13466. return false;
  13467. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  13468. return false;
  13469. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  13470. return false;
  13471. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  13472. return false;
  13473. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  13474. return false;
  13475. return true;
  13476. };
  13477. return BoundingInfo;
  13478. }());
  13479. BABYLON.BoundingInfo = BoundingInfo;
  13480. })(BABYLON || (BABYLON = {}));
  13481. //# sourceMappingURL=babylon.boundingInfo.js.map
  13482. var BABYLON;
  13483. (function (BABYLON) {
  13484. var TransformNode = /** @class */ (function (_super) {
  13485. __extends(TransformNode, _super);
  13486. function TransformNode(name, scene, isPure) {
  13487. if (scene === void 0) { scene = null; }
  13488. if (isPure === void 0) { isPure = true; }
  13489. var _this = _super.call(this, name, scene) || this;
  13490. // Properties
  13491. _this._rotation = BABYLON.Vector3.Zero();
  13492. _this._scaling = BABYLON.Vector3.One();
  13493. _this._isDirty = false;
  13494. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  13495. _this.scalingDeterminant = 1;
  13496. _this.infiniteDistance = false;
  13497. _this.position = BABYLON.Vector3.Zero();
  13498. _this._localWorld = BABYLON.Matrix.Zero();
  13499. _this._worldMatrix = BABYLON.Matrix.Zero();
  13500. _this._worldMatrixDeterminant = 0;
  13501. _this._absolutePosition = BABYLON.Vector3.Zero();
  13502. _this._pivotMatrix = BABYLON.Matrix.Identity();
  13503. _this._postMultiplyPivotMatrix = false;
  13504. _this._isWorldMatrixFrozen = false;
  13505. /**
  13506. * An event triggered after the world matrix is updated
  13507. * @type {BABYLON.Observable}
  13508. */
  13509. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  13510. _this._nonUniformScaling = false;
  13511. if (isPure) {
  13512. _this.getScene().addTransformNode(_this);
  13513. }
  13514. return _this;
  13515. }
  13516. Object.defineProperty(TransformNode.prototype, "rotation", {
  13517. /**
  13518. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  13519. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  13520. * Default : (0.0, 0.0, 0.0)
  13521. */
  13522. get: function () {
  13523. return this._rotation;
  13524. },
  13525. set: function (newRotation) {
  13526. this._rotation = newRotation;
  13527. },
  13528. enumerable: true,
  13529. configurable: true
  13530. });
  13531. Object.defineProperty(TransformNode.prototype, "scaling", {
  13532. /**
  13533. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  13534. * Default : (1.0, 1.0, 1.0)
  13535. */
  13536. get: function () {
  13537. return this._scaling;
  13538. },
  13539. /**
  13540. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  13541. * Default : (1.0, 1.0, 1.0)
  13542. */
  13543. set: function (newScaling) {
  13544. this._scaling = newScaling;
  13545. },
  13546. enumerable: true,
  13547. configurable: true
  13548. });
  13549. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  13550. /**
  13551. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  13552. * It's null by default.
  13553. * 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)
  13554. */
  13555. get: function () {
  13556. return this._rotationQuaternion;
  13557. },
  13558. set: function (quaternion) {
  13559. this._rotationQuaternion = quaternion;
  13560. //reset the rotation vector.
  13561. if (quaternion && this.rotation.length()) {
  13562. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  13563. }
  13564. },
  13565. enumerable: true,
  13566. configurable: true
  13567. });
  13568. /**
  13569. * Returns the latest update of the World matrix
  13570. * Returns a Matrix.
  13571. */
  13572. TransformNode.prototype.getWorldMatrix = function () {
  13573. if (this._currentRenderId !== this.getScene().getRenderId()) {
  13574. this.computeWorldMatrix();
  13575. }
  13576. return this._worldMatrix;
  13577. };
  13578. /**
  13579. * Returns the latest update of the World matrix determinant.
  13580. */
  13581. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  13582. if (this._currentRenderId !== this.getScene().getRenderId()) {
  13583. this.computeWorldMatrix();
  13584. }
  13585. return this._worldMatrixDeterminant;
  13586. };
  13587. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  13588. /**
  13589. * Returns directly the latest state of the mesh World matrix.
  13590. * A Matrix is returned.
  13591. */
  13592. get: function () {
  13593. return this._worldMatrix;
  13594. },
  13595. enumerable: true,
  13596. configurable: true
  13597. });
  13598. /**
  13599. * Copies the paramater passed Matrix into the mesh Pose matrix.
  13600. * Returns the AbstractMesh.
  13601. */
  13602. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  13603. this._poseMatrix.copyFrom(matrix);
  13604. return this;
  13605. };
  13606. /**
  13607. * Returns the mesh Pose matrix.
  13608. * Returned object : Matrix
  13609. */
  13610. TransformNode.prototype.getPoseMatrix = function () {
  13611. return this._poseMatrix;
  13612. };
  13613. TransformNode.prototype._isSynchronized = function () {
  13614. if (this._isDirty) {
  13615. return false;
  13616. }
  13617. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  13618. return false;
  13619. if (this._cache.pivotMatrixUpdated) {
  13620. return false;
  13621. }
  13622. if (this.infiniteDistance) {
  13623. return false;
  13624. }
  13625. if (!this._cache.position.equals(this.position))
  13626. return false;
  13627. if (this.rotationQuaternion) {
  13628. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  13629. return false;
  13630. }
  13631. if (!this._cache.rotation.equals(this.rotation))
  13632. return false;
  13633. if (!this._cache.scaling.equals(this.scaling))
  13634. return false;
  13635. return true;
  13636. };
  13637. TransformNode.prototype._initCache = function () {
  13638. _super.prototype._initCache.call(this);
  13639. this._cache.localMatrixUpdated = false;
  13640. this._cache.position = BABYLON.Vector3.Zero();
  13641. this._cache.scaling = BABYLON.Vector3.Zero();
  13642. this._cache.rotation = BABYLON.Vector3.Zero();
  13643. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  13644. this._cache.billboardMode = -1;
  13645. };
  13646. TransformNode.prototype.markAsDirty = function (property) {
  13647. if (property === "rotation") {
  13648. this.rotationQuaternion = null;
  13649. }
  13650. this._currentRenderId = Number.MAX_VALUE;
  13651. this._isDirty = true;
  13652. return this;
  13653. };
  13654. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  13655. /**
  13656. * Returns the current mesh absolute position.
  13657. * Retuns a Vector3.
  13658. */
  13659. get: function () {
  13660. return this._absolutePosition;
  13661. },
  13662. enumerable: true,
  13663. configurable: true
  13664. });
  13665. /**
  13666. * Sets a new pivot matrix to the mesh.
  13667. * Returns the AbstractMesh.
  13668. */
  13669. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  13670. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  13671. this._pivotMatrix = matrix.clone();
  13672. this._cache.pivotMatrixUpdated = true;
  13673. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  13674. if (this._postMultiplyPivotMatrix) {
  13675. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  13676. }
  13677. return this;
  13678. };
  13679. /**
  13680. * Returns the mesh pivot matrix.
  13681. * Default : Identity.
  13682. * A Matrix is returned.
  13683. */
  13684. TransformNode.prototype.getPivotMatrix = function () {
  13685. return this._pivotMatrix;
  13686. };
  13687. /**
  13688. * Prevents the World matrix to be computed any longer.
  13689. * Returns the AbstractMesh.
  13690. */
  13691. TransformNode.prototype.freezeWorldMatrix = function () {
  13692. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  13693. this.computeWorldMatrix(true);
  13694. this._isWorldMatrixFrozen = true;
  13695. return this;
  13696. };
  13697. /**
  13698. * Allows back the World matrix computation.
  13699. * Returns the AbstractMesh.
  13700. */
  13701. TransformNode.prototype.unfreezeWorldMatrix = function () {
  13702. this._isWorldMatrixFrozen = false;
  13703. this.computeWorldMatrix(true);
  13704. return this;
  13705. };
  13706. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  13707. /**
  13708. * True if the World matrix has been frozen.
  13709. * Returns a boolean.
  13710. */
  13711. get: function () {
  13712. return this._isWorldMatrixFrozen;
  13713. },
  13714. enumerable: true,
  13715. configurable: true
  13716. });
  13717. /**
  13718. * Retuns the mesh absolute position in the World.
  13719. * Returns a Vector3.
  13720. */
  13721. TransformNode.prototype.getAbsolutePosition = function () {
  13722. this.computeWorldMatrix();
  13723. return this._absolutePosition;
  13724. };
  13725. /**
  13726. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  13727. * Returns the AbstractMesh.
  13728. */
  13729. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  13730. if (!absolutePosition) {
  13731. return this;
  13732. }
  13733. var absolutePositionX;
  13734. var absolutePositionY;
  13735. var absolutePositionZ;
  13736. if (absolutePosition.x === undefined) {
  13737. if (arguments.length < 3) {
  13738. return this;
  13739. }
  13740. absolutePositionX = arguments[0];
  13741. absolutePositionY = arguments[1];
  13742. absolutePositionZ = arguments[2];
  13743. }
  13744. else {
  13745. absolutePositionX = absolutePosition.x;
  13746. absolutePositionY = absolutePosition.y;
  13747. absolutePositionZ = absolutePosition.z;
  13748. }
  13749. if (this.parent) {
  13750. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13751. invertParentWorldMatrix.invert();
  13752. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  13753. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  13754. }
  13755. else {
  13756. this.position.x = absolutePositionX;
  13757. this.position.y = absolutePositionY;
  13758. this.position.z = absolutePositionZ;
  13759. }
  13760. return this;
  13761. };
  13762. /**
  13763. * Sets the mesh position in its local space.
  13764. * Returns the AbstractMesh.
  13765. */
  13766. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  13767. this.computeWorldMatrix();
  13768. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  13769. return this;
  13770. };
  13771. /**
  13772. * Returns the mesh position in the local space from the current World matrix values.
  13773. * Returns a new Vector3.
  13774. */
  13775. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  13776. this.computeWorldMatrix();
  13777. var invLocalWorldMatrix = this._localWorld.clone();
  13778. invLocalWorldMatrix.invert();
  13779. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  13780. };
  13781. /**
  13782. * Translates the mesh along the passed Vector3 in its local space.
  13783. * Returns the AbstractMesh.
  13784. */
  13785. TransformNode.prototype.locallyTranslate = function (vector3) {
  13786. this.computeWorldMatrix(true);
  13787. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  13788. return this;
  13789. };
  13790. /**
  13791. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  13792. * @param targetPoint the position (must be in same space as current mesh) to look at
  13793. * @param yawCor optional yaw (y-axis) correction in radians
  13794. * @param pitchCor optional pitch (x-axis) correction in radians
  13795. * @param rollCor optional roll (z-axis) correction in radians
  13796. * @param space the choosen space of the target
  13797. * @returns the TransformNode.
  13798. */
  13799. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  13800. if (yawCor === void 0) { yawCor = 0; }
  13801. if (pitchCor === void 0) { pitchCor = 0; }
  13802. if (rollCor === void 0) { rollCor = 0; }
  13803. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13804. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  13805. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  13806. targetPoint.subtractToRef(pos, dv);
  13807. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  13808. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  13809. var pitch = Math.atan2(dv.y, len);
  13810. if (this.rotationQuaternion) {
  13811. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  13812. }
  13813. else {
  13814. this.rotation.x = pitch + pitchCor;
  13815. this.rotation.y = yaw + yawCor;
  13816. this.rotation.z = rollCor;
  13817. }
  13818. return this;
  13819. };
  13820. /**
  13821. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  13822. * This Vector3 is expressed in the World space.
  13823. */
  13824. TransformNode.prototype.getDirection = function (localAxis) {
  13825. var result = BABYLON.Vector3.Zero();
  13826. this.getDirectionToRef(localAxis, result);
  13827. return result;
  13828. };
  13829. /**
  13830. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  13831. * localAxis is expressed in the mesh local space.
  13832. * result is computed in the Wordl space from the mesh World matrix.
  13833. * Returns the AbstractMesh.
  13834. */
  13835. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  13836. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13837. return this;
  13838. };
  13839. TransformNode.prototype.setPivotPoint = function (point, space) {
  13840. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13841. if (this.getScene().getRenderId() == 0) {
  13842. this.computeWorldMatrix(true);
  13843. }
  13844. var wm = this.getWorldMatrix();
  13845. if (space == BABYLON.Space.WORLD) {
  13846. var tmat = BABYLON.Tmp.Matrix[0];
  13847. wm.invertToRef(tmat);
  13848. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  13849. }
  13850. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  13851. this._pivotMatrix.m[12] = -point.x;
  13852. this._pivotMatrix.m[13] = -point.y;
  13853. this._pivotMatrix.m[14] = -point.z;
  13854. this._cache.pivotMatrixUpdated = true;
  13855. return this;
  13856. };
  13857. /**
  13858. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  13859. */
  13860. TransformNode.prototype.getPivotPoint = function () {
  13861. var point = BABYLON.Vector3.Zero();
  13862. this.getPivotPointToRef(point);
  13863. return point;
  13864. };
  13865. /**
  13866. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  13867. * Returns the AbstractMesh.
  13868. */
  13869. TransformNode.prototype.getPivotPointToRef = function (result) {
  13870. result.x = -this._pivotMatrix.m[12];
  13871. result.y = -this._pivotMatrix.m[13];
  13872. result.z = -this._pivotMatrix.m[14];
  13873. return this;
  13874. };
  13875. /**
  13876. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  13877. */
  13878. TransformNode.prototype.getAbsolutePivotPoint = function () {
  13879. var point = BABYLON.Vector3.Zero();
  13880. this.getAbsolutePivotPointToRef(point);
  13881. return point;
  13882. };
  13883. /**
  13884. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  13885. * Returns the AbstractMesh.
  13886. */
  13887. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  13888. result.x = this._pivotMatrix.m[12];
  13889. result.y = this._pivotMatrix.m[13];
  13890. result.z = this._pivotMatrix.m[14];
  13891. this.getPivotPointToRef(result);
  13892. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  13893. return this;
  13894. };
  13895. /**
  13896. * Defines the passed node as the parent of the current node.
  13897. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  13898. * Returns the TransformNode.
  13899. */
  13900. TransformNode.prototype.setParent = function (node) {
  13901. if (node === null) {
  13902. var rotation = BABYLON.Tmp.Quaternion[0];
  13903. var position = BABYLON.Tmp.Vector3[0];
  13904. var scale = BABYLON.Tmp.Vector3[1];
  13905. if (this.parent && this.parent.computeWorldMatrix) {
  13906. this.parent.computeWorldMatrix(true);
  13907. }
  13908. this.computeWorldMatrix(true);
  13909. this.getWorldMatrix().decompose(scale, rotation, position);
  13910. if (this.rotationQuaternion) {
  13911. this.rotationQuaternion.copyFrom(rotation);
  13912. }
  13913. else {
  13914. rotation.toEulerAnglesToRef(this.rotation);
  13915. }
  13916. this.scaling.x = scale.x;
  13917. this.scaling.y = scale.y;
  13918. this.scaling.z = scale.z;
  13919. this.position.x = position.x;
  13920. this.position.y = position.y;
  13921. this.position.z = position.z;
  13922. }
  13923. else {
  13924. var rotation = BABYLON.Tmp.Quaternion[0];
  13925. var position = BABYLON.Tmp.Vector3[0];
  13926. var scale = BABYLON.Tmp.Vector3[1];
  13927. var diffMatrix = BABYLON.Tmp.Matrix[0];
  13928. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  13929. this.computeWorldMatrix(true);
  13930. node.computeWorldMatrix(true);
  13931. node.getWorldMatrix().invertToRef(invParentMatrix);
  13932. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  13933. diffMatrix.decompose(scale, rotation, position);
  13934. if (this.rotationQuaternion) {
  13935. this.rotationQuaternion.copyFrom(rotation);
  13936. }
  13937. else {
  13938. rotation.toEulerAnglesToRef(this.rotation);
  13939. }
  13940. this.position.x = position.x;
  13941. this.position.y = position.y;
  13942. this.position.z = position.z;
  13943. this.scaling.x = scale.x;
  13944. this.scaling.y = scale.y;
  13945. this.scaling.z = scale.z;
  13946. }
  13947. this.parent = node;
  13948. return this;
  13949. };
  13950. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  13951. get: function () {
  13952. return this._nonUniformScaling;
  13953. },
  13954. enumerable: true,
  13955. configurable: true
  13956. });
  13957. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  13958. if (this._nonUniformScaling === value) {
  13959. return false;
  13960. }
  13961. this._nonUniformScaling = true;
  13962. return true;
  13963. };
  13964. /**
  13965. * Attach the current TransformNode to another TransformNode associated with a bone
  13966. * @param bone Bone affecting the TransformNode
  13967. * @param affectedTransformNode TransformNode associated with the bone
  13968. */
  13969. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  13970. this._transformToBoneReferal = affectedTransformNode;
  13971. this.parent = bone;
  13972. if (bone.getWorldMatrix().determinant() < 0) {
  13973. this.scalingDeterminant *= -1;
  13974. }
  13975. return this;
  13976. };
  13977. TransformNode.prototype.detachFromBone = function () {
  13978. if (!this.parent) {
  13979. return this;
  13980. }
  13981. if (this.parent.getWorldMatrix().determinant() < 0) {
  13982. this.scalingDeterminant *= -1;
  13983. }
  13984. this._transformToBoneReferal = null;
  13985. this.parent = null;
  13986. return this;
  13987. };
  13988. /**
  13989. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  13990. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13991. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13992. * The passed axis is also normalized.
  13993. * Returns the AbstractMesh.
  13994. */
  13995. TransformNode.prototype.rotate = function (axis, amount, space) {
  13996. axis.normalize();
  13997. if (!this.rotationQuaternion) {
  13998. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13999. this.rotation = BABYLON.Vector3.Zero();
  14000. }
  14001. var rotationQuaternion;
  14002. if (!space || space === BABYLON.Space.LOCAL) {
  14003. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  14004. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  14005. }
  14006. else {
  14007. if (this.parent) {
  14008. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  14009. invertParentWorldMatrix.invert();
  14010. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  14011. }
  14012. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  14013. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  14014. }
  14015. return this;
  14016. };
  14017. /**
  14018. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  14019. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  14020. * The passed axis is also normalized.
  14021. * Returns the AbstractMesh.
  14022. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  14023. */
  14024. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  14025. axis.normalize();
  14026. if (!this.rotationQuaternion) {
  14027. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  14028. this.rotation.copyFromFloats(0, 0, 0);
  14029. }
  14030. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  14031. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  14032. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  14033. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  14034. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  14035. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  14036. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  14037. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  14038. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  14039. return this;
  14040. };
  14041. /**
  14042. * Translates the mesh along the axis vector for the passed distance in the given space.
  14043. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  14044. * Returns the AbstractMesh.
  14045. */
  14046. TransformNode.prototype.translate = function (axis, distance, space) {
  14047. var displacementVector = axis.scale(distance);
  14048. if (!space || space === BABYLON.Space.LOCAL) {
  14049. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  14050. this.setPositionWithLocalVector(tempV3);
  14051. }
  14052. else {
  14053. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  14054. }
  14055. return this;
  14056. };
  14057. /**
  14058. * Adds a rotation step to the mesh current rotation.
  14059. * x, y, z are Euler angles expressed in radians.
  14060. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  14061. * This means this rotation is made in the mesh local space only.
  14062. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  14063. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  14064. * ```javascript
  14065. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  14066. * ```
  14067. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  14068. * 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.
  14069. * Returns the AbstractMesh.
  14070. */
  14071. TransformNode.prototype.addRotation = function (x, y, z) {
  14072. var rotationQuaternion;
  14073. if (this.rotationQuaternion) {
  14074. rotationQuaternion = this.rotationQuaternion;
  14075. }
  14076. else {
  14077. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  14078. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  14079. }
  14080. var accumulation = BABYLON.Tmp.Quaternion[0];
  14081. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  14082. rotationQuaternion.multiplyInPlace(accumulation);
  14083. if (!this.rotationQuaternion) {
  14084. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  14085. }
  14086. return this;
  14087. };
  14088. /**
  14089. * Computes the mesh World matrix and returns it.
  14090. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  14091. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  14092. * If the parameter `force`is set to `true`, the actual computation is done.
  14093. * Returns the mesh World Matrix.
  14094. */
  14095. TransformNode.prototype.computeWorldMatrix = function (force) {
  14096. if (this._isWorldMatrixFrozen) {
  14097. return this._worldMatrix;
  14098. }
  14099. if (!force && this.isSynchronized(true)) {
  14100. return this._worldMatrix;
  14101. }
  14102. this._cache.position.copyFrom(this.position);
  14103. this._cache.scaling.copyFrom(this.scaling);
  14104. this._cache.pivotMatrixUpdated = false;
  14105. this._cache.billboardMode = this.billboardMode;
  14106. this._currentRenderId = this.getScene().getRenderId();
  14107. this._isDirty = false;
  14108. // Scaling
  14109. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  14110. // Rotation
  14111. //rotate, if quaternion is set and rotation was used
  14112. if (this.rotationQuaternion) {
  14113. var len = this.rotation.length();
  14114. if (len) {
  14115. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  14116. this.rotation.copyFromFloats(0, 0, 0);
  14117. }
  14118. }
  14119. if (this.rotationQuaternion) {
  14120. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  14121. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14122. }
  14123. else {
  14124. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  14125. this._cache.rotation.copyFrom(this.rotation);
  14126. }
  14127. // Translation
  14128. var camera = this.getScene().activeCamera;
  14129. if (this.infiniteDistance && !this.parent && camera) {
  14130. var cameraWorldMatrix = camera.getWorldMatrix();
  14131. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  14132. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  14133. }
  14134. else {
  14135. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  14136. }
  14137. // Composing transformations
  14138. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  14139. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  14140. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  14141. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  14142. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  14143. // Need to decompose each rotation here
  14144. var currentPosition = BABYLON.Tmp.Vector3[3];
  14145. if (this.parent && this.parent.getWorldMatrix) {
  14146. if (this._transformToBoneReferal) {
  14147. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  14148. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  14149. }
  14150. else {
  14151. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  14152. }
  14153. }
  14154. else {
  14155. currentPosition.copyFrom(this.position);
  14156. }
  14157. currentPosition.subtractInPlace(camera.globalPosition);
  14158. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  14159. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  14160. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  14161. }
  14162. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  14163. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  14164. }
  14165. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  14166. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  14167. }
  14168. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  14169. }
  14170. else {
  14171. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  14172. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  14173. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  14174. }
  14175. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  14176. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  14177. }
  14178. // Local world
  14179. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  14180. // Parent
  14181. if (this.parent && this.parent.getWorldMatrix) {
  14182. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  14183. if (this._transformToBoneReferal) {
  14184. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  14185. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  14186. }
  14187. else {
  14188. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  14189. }
  14190. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  14191. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  14192. this._worldMatrix.copyFrom(this._localWorld);
  14193. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  14194. }
  14195. else {
  14196. if (this._transformToBoneReferal) {
  14197. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  14198. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  14199. }
  14200. else {
  14201. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  14202. }
  14203. }
  14204. this._markSyncedWithParent();
  14205. }
  14206. else {
  14207. this._worldMatrix.copyFrom(this._localWorld);
  14208. }
  14209. // Post multiply inverse of pivotMatrix
  14210. if (this._postMultiplyPivotMatrix) {
  14211. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  14212. }
  14213. // Normal matrix
  14214. if (this.scaling.isNonUniform) {
  14215. this._updateNonUniformScalingState(true);
  14216. }
  14217. else if (this.parent && this.parent._nonUniformScaling) {
  14218. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  14219. }
  14220. else {
  14221. this._updateNonUniformScalingState(false);
  14222. }
  14223. this._afterComputeWorldMatrix();
  14224. // Absolute position
  14225. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  14226. // Callbacks
  14227. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  14228. if (!this._poseMatrix) {
  14229. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  14230. }
  14231. // Cache the determinant
  14232. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  14233. return this._worldMatrix;
  14234. };
  14235. TransformNode.prototype._afterComputeWorldMatrix = function () {
  14236. };
  14237. /**
  14238. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  14239. * @param func: callback function to add
  14240. *
  14241. * Returns the TransformNode.
  14242. */
  14243. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  14244. this.onAfterWorldMatrixUpdateObservable.add(func);
  14245. return this;
  14246. };
  14247. /**
  14248. * Removes a registered callback function.
  14249. * Returns the TransformNode.
  14250. */
  14251. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  14252. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  14253. return this;
  14254. };
  14255. /**
  14256. * Clone the current transform node
  14257. * Returns the new transform node
  14258. * @param name Name of the new clone
  14259. * @param newParent New parent for the clone
  14260. * @param doNotCloneChildren Do not clone children hierarchy
  14261. */
  14262. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14263. var _this = this;
  14264. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  14265. result.name = name;
  14266. result.id = name;
  14267. if (newParent) {
  14268. result.parent = newParent;
  14269. }
  14270. if (!doNotCloneChildren) {
  14271. // Children
  14272. var directDescendants = this.getDescendants(true);
  14273. for (var index = 0; index < directDescendants.length; index++) {
  14274. var child = directDescendants[index];
  14275. if (child.clone) {
  14276. child.clone(name + "." + child.name, result);
  14277. }
  14278. }
  14279. }
  14280. return result;
  14281. };
  14282. TransformNode.prototype.serialize = function (currentSerializationObject) {
  14283. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  14284. serializationObject.type = this.getClassName();
  14285. // Parent
  14286. if (this.parent) {
  14287. serializationObject.parentId = this.parent.id;
  14288. }
  14289. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  14290. serializationObject.tags = BABYLON.Tags.GetTags(this);
  14291. }
  14292. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  14293. serializationObject.isEnabled = this.isEnabled();
  14294. // Parent
  14295. if (this.parent) {
  14296. serializationObject.parentId = this.parent.id;
  14297. }
  14298. return serializationObject;
  14299. };
  14300. // Statics
  14301. /**
  14302. * Returns a new TransformNode object parsed from the source provided.
  14303. * The parameter `parsedMesh` is the source.
  14304. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  14305. */
  14306. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  14307. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  14308. if (BABYLON.Tags) {
  14309. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  14310. }
  14311. if (parsedTransformNode.localMatrix) {
  14312. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  14313. }
  14314. else if (parsedTransformNode.pivotMatrix) {
  14315. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  14316. }
  14317. transformNode.setEnabled(parsedTransformNode.isEnabled);
  14318. // Parent
  14319. if (parsedTransformNode.parentId) {
  14320. transformNode._waitingParentId = parsedTransformNode.parentId;
  14321. }
  14322. return transformNode;
  14323. };
  14324. /**
  14325. * Disposes the TransformNode.
  14326. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  14327. * Returns nothing.
  14328. */
  14329. TransformNode.prototype.dispose = function (doNotRecurse) {
  14330. // Animations
  14331. this.getScene().stopAnimation(this);
  14332. // Remove from scene
  14333. this.getScene().removeTransformNode(this);
  14334. this._cache = {};
  14335. if (!doNotRecurse) {
  14336. // Children
  14337. var objects = this.getDescendants(true);
  14338. for (var index = 0; index < objects.length; index++) {
  14339. objects[index].dispose();
  14340. }
  14341. }
  14342. else {
  14343. var childMeshes = this.getChildMeshes(true);
  14344. for (index = 0; index < childMeshes.length; index++) {
  14345. var child = childMeshes[index];
  14346. child.parent = null;
  14347. child.computeWorldMatrix(true);
  14348. }
  14349. }
  14350. this.onAfterWorldMatrixUpdateObservable.clear();
  14351. _super.prototype.dispose.call(this);
  14352. };
  14353. // Statics
  14354. TransformNode.BILLBOARDMODE_NONE = 0;
  14355. TransformNode.BILLBOARDMODE_X = 1;
  14356. TransformNode.BILLBOARDMODE_Y = 2;
  14357. TransformNode.BILLBOARDMODE_Z = 4;
  14358. TransformNode.BILLBOARDMODE_ALL = 7;
  14359. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  14360. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  14361. __decorate([
  14362. BABYLON.serializeAsVector3()
  14363. ], TransformNode.prototype, "_rotation", void 0);
  14364. __decorate([
  14365. BABYLON.serializeAsQuaternion()
  14366. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  14367. __decorate([
  14368. BABYLON.serializeAsVector3()
  14369. ], TransformNode.prototype, "_scaling", void 0);
  14370. __decorate([
  14371. BABYLON.serialize()
  14372. ], TransformNode.prototype, "billboardMode", void 0);
  14373. __decorate([
  14374. BABYLON.serialize()
  14375. ], TransformNode.prototype, "scalingDeterminant", void 0);
  14376. __decorate([
  14377. BABYLON.serialize()
  14378. ], TransformNode.prototype, "infiniteDistance", void 0);
  14379. __decorate([
  14380. BABYLON.serializeAsVector3()
  14381. ], TransformNode.prototype, "position", void 0);
  14382. return TransformNode;
  14383. }(BABYLON.Node));
  14384. BABYLON.TransformNode = TransformNode;
  14385. })(BABYLON || (BABYLON = {}));
  14386. //# sourceMappingURL=babylon.transformNode.js.map
  14387. var BABYLON;
  14388. (function (BABYLON) {
  14389. var AbstractMesh = /** @class */ (function (_super) {
  14390. __extends(AbstractMesh, _super);
  14391. // Constructor
  14392. function AbstractMesh(name, scene) {
  14393. if (scene === void 0) { scene = null; }
  14394. var _this = _super.call(this, name, scene, false) || this;
  14395. _this._facetNb = 0; // facet number
  14396. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  14397. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  14398. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  14399. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  14400. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  14401. _this._subDiv = {
  14402. max: 1,
  14403. X: 1,
  14404. Y: 1,
  14405. Z: 1
  14406. };
  14407. _this._facetDepthSort = false; // is the facet depth sort to be computed
  14408. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  14409. // Events
  14410. /**
  14411. * An event triggered when this mesh collides with another one
  14412. * @type {BABYLON.Observable}
  14413. */
  14414. _this.onCollideObservable = new BABYLON.Observable();
  14415. /**
  14416. * An event triggered when the collision's position changes
  14417. * @type {BABYLON.Observable}
  14418. */
  14419. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  14420. /**
  14421. * An event triggered when material is changed
  14422. * @type {BABYLON.Observable}
  14423. */
  14424. _this.onMaterialChangedObservable = new BABYLON.Observable();
  14425. // Properties
  14426. _this.definedFacingForward = true; // orientation for POV movement & rotation
  14427. /**
  14428. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  14429. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  14430. * or
  14431. * 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.
  14432. * for more info check WebGl documentations
  14433. */
  14434. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  14435. /**
  14436. * 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:
  14437. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  14438. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  14439. * 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.
  14440. */
  14441. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  14442. /**
  14443. * 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.
  14444. * The default value is -1 which means don't break the query and wait till the result.
  14445. */
  14446. _this.occlusionRetryCount = -1;
  14447. _this._occlusionInternalRetryCounter = 0;
  14448. _this._isOccluded = false;
  14449. _this._isOcclusionQueryInProgress = false;
  14450. _this.visibility = 1.0;
  14451. _this.alphaIndex = Number.MAX_VALUE;
  14452. _this.isVisible = true;
  14453. _this.isPickable = true;
  14454. _this.showBoundingBox = false;
  14455. _this.showSubMeshesBoundingBox = false;
  14456. _this.isBlocker = false;
  14457. _this.enablePointerMoveEvents = false;
  14458. _this.renderingGroupId = 0;
  14459. _this._receiveShadows = false;
  14460. _this.renderOutline = false;
  14461. _this.outlineColor = BABYLON.Color3.Red();
  14462. _this.outlineWidth = 0.02;
  14463. _this.renderOverlay = false;
  14464. _this.overlayColor = BABYLON.Color3.Red();
  14465. _this.overlayAlpha = 0.5;
  14466. _this._hasVertexAlpha = false;
  14467. _this._useVertexColors = true;
  14468. _this._computeBonesUsingShaders = true;
  14469. _this._numBoneInfluencers = 4;
  14470. _this._applyFog = true;
  14471. _this.useOctreeForRenderingSelection = true;
  14472. _this.useOctreeForPicking = true;
  14473. _this.useOctreeForCollisions = true;
  14474. _this._layerMask = 0x0FFFFFFF;
  14475. /**
  14476. * True if the mesh must be rendered in any case.
  14477. */
  14478. _this.alwaysSelectAsActiveMesh = false;
  14479. /**
  14480. * This scene's action manager
  14481. * @type {BABYLON.ActionManager}
  14482. */
  14483. _this.actionManager = null;
  14484. // Physics
  14485. _this.physicsImpostor = null;
  14486. // Collisions
  14487. _this._checkCollisions = false;
  14488. _this._collisionMask = -1;
  14489. _this._collisionGroup = -1;
  14490. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  14491. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  14492. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  14493. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  14494. // Edges
  14495. _this.edgesWidth = 1;
  14496. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  14497. // Cache
  14498. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  14499. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  14500. _this._isDisposed = false;
  14501. _this._renderId = 0;
  14502. _this._intersectionsInProgress = new Array();
  14503. _this._unIndexed = false;
  14504. _this._lightSources = new Array();
  14505. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  14506. if (collidedMesh === void 0) { collidedMesh = null; }
  14507. //TODO move this to the collision coordinator!
  14508. if (_this.getScene().workerCollisions)
  14509. newPosition.multiplyInPlace(_this._collider._radius);
  14510. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  14511. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  14512. _this.position.addInPlace(_this._diffPositionForCollisions);
  14513. }
  14514. if (collidedMesh) {
  14515. _this.onCollideObservable.notifyObservers(collidedMesh);
  14516. }
  14517. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  14518. };
  14519. _this.getScene().addMesh(_this);
  14520. _this._resyncLightSources();
  14521. return _this;
  14522. }
  14523. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  14524. get: function () {
  14525. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  14526. },
  14527. enumerable: true,
  14528. configurable: true
  14529. });
  14530. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  14531. get: function () {
  14532. return BABYLON.TransformNode.BILLBOARDMODE_X;
  14533. },
  14534. enumerable: true,
  14535. configurable: true
  14536. });
  14537. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  14538. get: function () {
  14539. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  14540. },
  14541. enumerable: true,
  14542. configurable: true
  14543. });
  14544. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  14545. get: function () {
  14546. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  14547. },
  14548. enumerable: true,
  14549. configurable: true
  14550. });
  14551. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  14552. get: function () {
  14553. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  14554. },
  14555. enumerable: true,
  14556. configurable: true
  14557. });
  14558. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  14559. /**
  14560. * Read-only : the number of facets in the mesh
  14561. */
  14562. get: function () {
  14563. return this._facetNb;
  14564. },
  14565. enumerable: true,
  14566. configurable: true
  14567. });
  14568. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  14569. /**
  14570. * The number (integer) of subdivisions per axis in the partioning space
  14571. */
  14572. get: function () {
  14573. return this._partitioningSubdivisions;
  14574. },
  14575. set: function (nb) {
  14576. this._partitioningSubdivisions = nb;
  14577. },
  14578. enumerable: true,
  14579. configurable: true
  14580. });
  14581. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  14582. /**
  14583. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  14584. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  14585. */
  14586. get: function () {
  14587. return this._partitioningBBoxRatio;
  14588. },
  14589. set: function (ratio) {
  14590. this._partitioningBBoxRatio = ratio;
  14591. },
  14592. enumerable: true,
  14593. configurable: true
  14594. });
  14595. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  14596. /**
  14597. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  14598. * Works only for updatable meshes.
  14599. * Doesn't work with multi-materials.
  14600. */
  14601. get: function () {
  14602. return this._facetDepthSort;
  14603. },
  14604. set: function (sort) {
  14605. this._facetDepthSort = sort;
  14606. },
  14607. enumerable: true,
  14608. configurable: true
  14609. });
  14610. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  14611. /**
  14612. * The location (Vector3) where the facet depth sort must be computed from.
  14613. * By default, the active camera position.
  14614. * Used only when facet depth sort is enabled.
  14615. */
  14616. get: function () {
  14617. return this._facetDepthSortFrom;
  14618. },
  14619. set: function (location) {
  14620. this._facetDepthSortFrom = location;
  14621. },
  14622. enumerable: true,
  14623. configurable: true
  14624. });
  14625. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  14626. /**
  14627. * Read-only boolean : is the feature facetData enabled ?
  14628. */
  14629. get: function () {
  14630. return this._facetDataEnabled;
  14631. },
  14632. enumerable: true,
  14633. configurable: true
  14634. });
  14635. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  14636. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  14637. return false;
  14638. }
  14639. this._markSubMeshesAsMiscDirty();
  14640. return true;
  14641. };
  14642. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  14643. set: function (callback) {
  14644. if (this._onCollideObserver) {
  14645. this.onCollideObservable.remove(this._onCollideObserver);
  14646. }
  14647. this._onCollideObserver = this.onCollideObservable.add(callback);
  14648. },
  14649. enumerable: true,
  14650. configurable: true
  14651. });
  14652. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  14653. set: function (callback) {
  14654. if (this._onCollisionPositionChangeObserver) {
  14655. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  14656. }
  14657. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  14658. },
  14659. enumerable: true,
  14660. configurable: true
  14661. });
  14662. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  14663. /**
  14664. * 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.
  14665. */
  14666. get: function () {
  14667. return this._isOccluded;
  14668. },
  14669. set: function (value) {
  14670. this._isOccluded = value;
  14671. },
  14672. enumerable: true,
  14673. configurable: true
  14674. });
  14675. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  14676. /**
  14677. * Flag to check the progress status of the query
  14678. */
  14679. get: function () {
  14680. return this._isOcclusionQueryInProgress;
  14681. },
  14682. enumerable: true,
  14683. configurable: true
  14684. });
  14685. Object.defineProperty(AbstractMesh.prototype, "material", {
  14686. get: function () {
  14687. return this._material;
  14688. },
  14689. set: function (value) {
  14690. if (this._material === value) {
  14691. return;
  14692. }
  14693. this._material = value;
  14694. if (this.onMaterialChangedObservable.hasObservers) {
  14695. this.onMaterialChangedObservable.notifyObservers(this);
  14696. }
  14697. if (!this.subMeshes) {
  14698. return;
  14699. }
  14700. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  14701. var subMesh = _a[_i];
  14702. subMesh.setEffect(null);
  14703. }
  14704. },
  14705. enumerable: true,
  14706. configurable: true
  14707. });
  14708. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  14709. get: function () {
  14710. return this._receiveShadows;
  14711. },
  14712. set: function (value) {
  14713. if (this._receiveShadows === value) {
  14714. return;
  14715. }
  14716. this._receiveShadows = value;
  14717. this._markSubMeshesAsLightDirty();
  14718. },
  14719. enumerable: true,
  14720. configurable: true
  14721. });
  14722. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  14723. get: function () {
  14724. return this._hasVertexAlpha;
  14725. },
  14726. set: function (value) {
  14727. if (this._hasVertexAlpha === value) {
  14728. return;
  14729. }
  14730. this._hasVertexAlpha = value;
  14731. this._markSubMeshesAsAttributesDirty();
  14732. },
  14733. enumerable: true,
  14734. configurable: true
  14735. });
  14736. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  14737. get: function () {
  14738. return this._useVertexColors;
  14739. },
  14740. set: function (value) {
  14741. if (this._useVertexColors === value) {
  14742. return;
  14743. }
  14744. this._useVertexColors = value;
  14745. this._markSubMeshesAsAttributesDirty();
  14746. },
  14747. enumerable: true,
  14748. configurable: true
  14749. });
  14750. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  14751. get: function () {
  14752. return this._computeBonesUsingShaders;
  14753. },
  14754. set: function (value) {
  14755. if (this._computeBonesUsingShaders === value) {
  14756. return;
  14757. }
  14758. this._computeBonesUsingShaders = value;
  14759. this._markSubMeshesAsAttributesDirty();
  14760. },
  14761. enumerable: true,
  14762. configurable: true
  14763. });
  14764. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  14765. get: function () {
  14766. return this._numBoneInfluencers;
  14767. },
  14768. set: function (value) {
  14769. if (this._numBoneInfluencers === value) {
  14770. return;
  14771. }
  14772. this._numBoneInfluencers = value;
  14773. this._markSubMeshesAsAttributesDirty();
  14774. },
  14775. enumerable: true,
  14776. configurable: true
  14777. });
  14778. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  14779. get: function () {
  14780. return this._applyFog;
  14781. },
  14782. set: function (value) {
  14783. if (this._applyFog === value) {
  14784. return;
  14785. }
  14786. this._applyFog = value;
  14787. this._markSubMeshesAsMiscDirty();
  14788. },
  14789. enumerable: true,
  14790. configurable: true
  14791. });
  14792. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  14793. get: function () {
  14794. return this._layerMask;
  14795. },
  14796. set: function (value) {
  14797. if (value === this._layerMask) {
  14798. return;
  14799. }
  14800. this._layerMask = value;
  14801. this._resyncLightSources();
  14802. },
  14803. enumerable: true,
  14804. configurable: true
  14805. });
  14806. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  14807. get: function () {
  14808. return this._collisionMask;
  14809. },
  14810. set: function (mask) {
  14811. this._collisionMask = !isNaN(mask) ? mask : -1;
  14812. },
  14813. enumerable: true,
  14814. configurable: true
  14815. });
  14816. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  14817. get: function () {
  14818. return this._collisionGroup;
  14819. },
  14820. set: function (mask) {
  14821. this._collisionGroup = !isNaN(mask) ? mask : -1;
  14822. },
  14823. enumerable: true,
  14824. configurable: true
  14825. });
  14826. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  14827. get: function () {
  14828. return null;
  14829. },
  14830. enumerable: true,
  14831. configurable: true
  14832. });
  14833. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  14834. get: function () {
  14835. return this._skeleton;
  14836. },
  14837. set: function (value) {
  14838. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  14839. this._skeleton._unregisterMeshWithPoseMatrix(this);
  14840. }
  14841. if (value && value.needInitialSkinMatrix) {
  14842. value._registerMeshWithPoseMatrix(this);
  14843. }
  14844. this._skeleton = value;
  14845. if (!this._skeleton) {
  14846. this._bonesTransformMatrices = null;
  14847. }
  14848. this._markSubMeshesAsAttributesDirty();
  14849. },
  14850. enumerable: true,
  14851. configurable: true
  14852. });
  14853. /**
  14854. * Boolean : true if the mesh has been disposed.
  14855. */
  14856. AbstractMesh.prototype.isDisposed = function () {
  14857. return this._isDisposed;
  14858. };
  14859. /**
  14860. * Returns the string "AbstractMesh"
  14861. */
  14862. AbstractMesh.prototype.getClassName = function () {
  14863. return "AbstractMesh";
  14864. };
  14865. /**
  14866. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14867. */
  14868. AbstractMesh.prototype.toString = function (fullDetails) {
  14869. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  14870. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  14871. if (this._skeleton) {
  14872. ret += ", skeleton: " + this._skeleton.name;
  14873. }
  14874. if (fullDetails) {
  14875. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  14876. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  14877. }
  14878. return ret;
  14879. };
  14880. AbstractMesh.prototype._rebuild = function () {
  14881. if (this._occlusionQuery) {
  14882. this._occlusionQuery = null;
  14883. }
  14884. if (this._edgesRenderer) {
  14885. this._edgesRenderer._rebuild();
  14886. }
  14887. if (!this.subMeshes) {
  14888. return;
  14889. }
  14890. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  14891. var subMesh = _a[_i];
  14892. subMesh._rebuild();
  14893. }
  14894. };
  14895. AbstractMesh.prototype._resyncLightSources = function () {
  14896. this._lightSources.length = 0;
  14897. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  14898. var light = _a[_i];
  14899. if (!light.isEnabled()) {
  14900. continue;
  14901. }
  14902. if (light.canAffectMesh(this)) {
  14903. this._lightSources.push(light);
  14904. }
  14905. }
  14906. this._markSubMeshesAsLightDirty();
  14907. };
  14908. AbstractMesh.prototype._resyncLighSource = function (light) {
  14909. var isIn = light.isEnabled() && light.canAffectMesh(this);
  14910. var index = this._lightSources.indexOf(light);
  14911. if (index === -1) {
  14912. if (!isIn) {
  14913. return;
  14914. }
  14915. this._lightSources.push(light);
  14916. }
  14917. else {
  14918. if (isIn) {
  14919. return;
  14920. }
  14921. this._lightSources.splice(index, 1);
  14922. }
  14923. this._markSubMeshesAsLightDirty();
  14924. };
  14925. AbstractMesh.prototype._removeLightSource = function (light) {
  14926. var index = this._lightSources.indexOf(light);
  14927. if (index === -1) {
  14928. return;
  14929. }
  14930. this._lightSources.splice(index, 1);
  14931. };
  14932. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  14933. if (!this.subMeshes) {
  14934. return;
  14935. }
  14936. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  14937. var subMesh = _a[_i];
  14938. if (subMesh._materialDefines) {
  14939. func(subMesh._materialDefines);
  14940. }
  14941. }
  14942. };
  14943. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  14944. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  14945. };
  14946. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  14947. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  14948. };
  14949. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  14950. if (!this.subMeshes) {
  14951. return;
  14952. }
  14953. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  14954. var subMesh = _a[_i];
  14955. var material = subMesh.getMaterial();
  14956. if (material) {
  14957. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  14958. }
  14959. }
  14960. };
  14961. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  14962. /**
  14963. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14964. * Default : (1.0, 1.0, 1.0)
  14965. */
  14966. get: function () {
  14967. return this._scaling;
  14968. },
  14969. /**
  14970. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14971. * Default : (1.0, 1.0, 1.0)
  14972. */
  14973. set: function (newScaling) {
  14974. this._scaling = newScaling;
  14975. if (this.physicsImpostor) {
  14976. this.physicsImpostor.forceUpdate();
  14977. }
  14978. },
  14979. enumerable: true,
  14980. configurable: true
  14981. });
  14982. // Methods
  14983. /**
  14984. * Disables the mesh edger rendering mode.
  14985. * Returns the AbstractMesh.
  14986. */
  14987. AbstractMesh.prototype.disableEdgesRendering = function () {
  14988. if (this._edgesRenderer) {
  14989. this._edgesRenderer.dispose();
  14990. this._edgesRenderer = null;
  14991. }
  14992. return this;
  14993. };
  14994. /**
  14995. * Enables the edge rendering mode on the mesh.
  14996. * This mode makes the mesh edges visible.
  14997. * Returns the AbstractMesh.
  14998. */
  14999. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  15000. if (epsilon === void 0) { epsilon = 0.95; }
  15001. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  15002. this.disableEdgesRendering();
  15003. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  15004. return this;
  15005. };
  15006. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  15007. /**
  15008. * Returns true if the mesh is blocked. Used by the class Mesh.
  15009. * Returns the boolean `false` by default.
  15010. */
  15011. get: function () {
  15012. return false;
  15013. },
  15014. enumerable: true,
  15015. configurable: true
  15016. });
  15017. /**
  15018. * Returns the mesh itself by default, used by the class Mesh.
  15019. * Returned type : AbstractMesh
  15020. */
  15021. AbstractMesh.prototype.getLOD = function (camera) {
  15022. return this;
  15023. };
  15024. /**
  15025. * Returns 0 by default, used by the class Mesh.
  15026. * Returns an integer.
  15027. */
  15028. AbstractMesh.prototype.getTotalVertices = function () {
  15029. return 0;
  15030. };
  15031. /**
  15032. * Returns null by default, used by the class Mesh.
  15033. * Returned type : integer array
  15034. */
  15035. AbstractMesh.prototype.getIndices = function () {
  15036. return null;
  15037. };
  15038. /**
  15039. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  15040. * Returned type : float array or Float32Array
  15041. */
  15042. AbstractMesh.prototype.getVerticesData = function (kind) {
  15043. return null;
  15044. };
  15045. /**
  15046. * Sets the vertex data of the mesh geometry for the requested `kind`.
  15047. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  15048. * The `data` are either a numeric array either a Float32Array.
  15049. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  15050. * 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).
  15051. * Note that a new underlying VertexBuffer object is created each call.
  15052. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  15053. *
  15054. * Possible `kind` values :
  15055. * - BABYLON.VertexBuffer.PositionKind
  15056. * - BABYLON.VertexBuffer.UVKind
  15057. * - BABYLON.VertexBuffer.UV2Kind
  15058. * - BABYLON.VertexBuffer.UV3Kind
  15059. * - BABYLON.VertexBuffer.UV4Kind
  15060. * - BABYLON.VertexBuffer.UV5Kind
  15061. * - BABYLON.VertexBuffer.UV6Kind
  15062. * - BABYLON.VertexBuffer.ColorKind
  15063. * - BABYLON.VertexBuffer.MatricesIndicesKind
  15064. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  15065. * - BABYLON.VertexBuffer.MatricesWeightsKind
  15066. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  15067. *
  15068. * Returns the Mesh.
  15069. */
  15070. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  15071. return this;
  15072. };
  15073. /**
  15074. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  15075. * If the mesh has no geometry, it is simply returned as it is.
  15076. * The `data` are either a numeric array either a Float32Array.
  15077. * No new underlying VertexBuffer object is created.
  15078. * 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.
  15079. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  15080. *
  15081. * Possible `kind` values :
  15082. * - BABYLON.VertexBuffer.PositionKind
  15083. * - BABYLON.VertexBuffer.UVKind
  15084. * - BABYLON.VertexBuffer.UV2Kind
  15085. * - BABYLON.VertexBuffer.UV3Kind
  15086. * - BABYLON.VertexBuffer.UV4Kind
  15087. * - BABYLON.VertexBuffer.UV5Kind
  15088. * - BABYLON.VertexBuffer.UV6Kind
  15089. * - BABYLON.VertexBuffer.ColorKind
  15090. * - BABYLON.VertexBuffer.MatricesIndicesKind
  15091. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  15092. * - BABYLON.VertexBuffer.MatricesWeightsKind
  15093. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  15094. *
  15095. * Returns the Mesh.
  15096. */
  15097. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  15098. return this;
  15099. };
  15100. /**
  15101. * Sets the mesh indices.
  15102. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  15103. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  15104. * This method creates a new index buffer each call.
  15105. * Returns the Mesh.
  15106. */
  15107. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  15108. return this;
  15109. };
  15110. /** Returns false by default, used by the class Mesh.
  15111. * Returns a boolean
  15112. */
  15113. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  15114. return false;
  15115. };
  15116. /**
  15117. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  15118. * Returns a BoundingInfo
  15119. */
  15120. AbstractMesh.prototype.getBoundingInfo = function () {
  15121. if (this._masterMesh) {
  15122. return this._masterMesh.getBoundingInfo();
  15123. }
  15124. if (!this._boundingInfo) {
  15125. // this._boundingInfo is being created here
  15126. this._updateBoundingInfo();
  15127. }
  15128. // cannot be null.
  15129. return this._boundingInfo;
  15130. };
  15131. /**
  15132. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  15133. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  15134. */
  15135. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  15136. if (includeDescendants === void 0) { includeDescendants = true; }
  15137. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  15138. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  15139. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  15140. if (maxDimension === 0) {
  15141. return this;
  15142. }
  15143. var scale = 1 / maxDimension;
  15144. this.scaling.scaleInPlace(scale);
  15145. return this;
  15146. };
  15147. /**
  15148. * Sets a mesh new object BoundingInfo.
  15149. * Returns the AbstractMesh.
  15150. */
  15151. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  15152. this._boundingInfo = boundingInfo;
  15153. return this;
  15154. };
  15155. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  15156. get: function () {
  15157. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  15158. },
  15159. enumerable: true,
  15160. configurable: true
  15161. });
  15162. AbstractMesh.prototype._preActivate = function () {
  15163. };
  15164. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  15165. };
  15166. AbstractMesh.prototype._activate = function (renderId) {
  15167. this._renderId = renderId;
  15168. };
  15169. /**
  15170. * Returns the latest update of the World matrix
  15171. * Returns a Matrix.
  15172. */
  15173. AbstractMesh.prototype.getWorldMatrix = function () {
  15174. if (this._masterMesh) {
  15175. return this._masterMesh.getWorldMatrix();
  15176. }
  15177. return _super.prototype.getWorldMatrix.call(this);
  15178. };
  15179. /**
  15180. * Returns the latest update of the World matrix determinant.
  15181. */
  15182. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  15183. if (this._masterMesh) {
  15184. return this._masterMesh._getWorldMatrixDeterminant();
  15185. }
  15186. return _super.prototype._getWorldMatrixDeterminant.call(this);
  15187. };
  15188. // ================================== Point of View Movement =================================
  15189. /**
  15190. * Perform relative position change from the point of view of behind the front of the mesh.
  15191. * This is performed taking into account the meshes current rotation, so you do not have to care.
  15192. * Supports definition of mesh facing forward or backward.
  15193. * @param {number} amountRight
  15194. * @param {number} amountUp
  15195. * @param {number} amountForward
  15196. *
  15197. * Returns the AbstractMesh.
  15198. */
  15199. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  15200. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  15201. return this;
  15202. };
  15203. /**
  15204. * Calculate relative position change from the point of view of behind the front of the mesh.
  15205. * This is performed taking into account the meshes current rotation, so you do not have to care.
  15206. * Supports definition of mesh facing forward or backward.
  15207. * @param {number} amountRight
  15208. * @param {number} amountUp
  15209. * @param {number} amountForward
  15210. *
  15211. * Returns a new Vector3.
  15212. */
  15213. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  15214. var rotMatrix = new BABYLON.Matrix();
  15215. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  15216. rotQuaternion.toRotationMatrix(rotMatrix);
  15217. var translationDelta = BABYLON.Vector3.Zero();
  15218. var defForwardMult = this.definedFacingForward ? -1 : 1;
  15219. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  15220. return translationDelta;
  15221. };
  15222. // ================================== Point of View Rotation =================================
  15223. /**
  15224. * Perform relative rotation change from the point of view of behind the front of the mesh.
  15225. * Supports definition of mesh facing forward or backward.
  15226. * @param {number} flipBack
  15227. * @param {number} twirlClockwise
  15228. * @param {number} tiltRight
  15229. *
  15230. * Returns the AbstractMesh.
  15231. */
  15232. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  15233. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  15234. return this;
  15235. };
  15236. /**
  15237. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  15238. * Supports definition of mesh facing forward or backward.
  15239. * @param {number} flipBack
  15240. * @param {number} twirlClockwise
  15241. * @param {number} tiltRight
  15242. *
  15243. * Returns a new Vector3.
  15244. */
  15245. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  15246. var defForwardMult = this.definedFacingForward ? 1 : -1;
  15247. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  15248. };
  15249. /**
  15250. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  15251. * @param includeDescendants Include bounding info from descendants as well (true by default).
  15252. */
  15253. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  15254. if (includeDescendants === void 0) { includeDescendants = true; }
  15255. this.computeWorldMatrix(true);
  15256. var min;
  15257. var max;
  15258. var boundingInfo = this.getBoundingInfo();
  15259. if (!this.subMeshes) {
  15260. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15261. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  15262. }
  15263. else {
  15264. min = boundingInfo.boundingBox.minimumWorld;
  15265. max = boundingInfo.boundingBox.maximumWorld;
  15266. }
  15267. if (includeDescendants) {
  15268. var descendants = this.getDescendants(false);
  15269. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  15270. var descendant = descendants_1[_i];
  15271. var childMesh = descendant;
  15272. childMesh.computeWorldMatrix(true);
  15273. //make sure we have the needed params to get mix and max
  15274. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  15275. continue;
  15276. }
  15277. var childBoundingInfo = childMesh.getBoundingInfo();
  15278. var boundingBox = childBoundingInfo.boundingBox;
  15279. var minBox = boundingBox.minimumWorld;
  15280. var maxBox = boundingBox.maximumWorld;
  15281. BABYLON.Tools.CheckExtends(minBox, min, max);
  15282. BABYLON.Tools.CheckExtends(maxBox, min, max);
  15283. }
  15284. }
  15285. return {
  15286. min: min,
  15287. max: max
  15288. };
  15289. };
  15290. /**
  15291. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  15292. * Returns the AbstractMesh.
  15293. */
  15294. AbstractMesh.prototype._updateBoundingInfo = function () {
  15295. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  15296. this._boundingInfo.update(this.worldMatrixFromCache);
  15297. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  15298. return this;
  15299. };
  15300. /**
  15301. * Update a mesh's children BoundingInfo objects only.
  15302. * Returns the AbstractMesh.
  15303. */
  15304. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  15305. if (!this.subMeshes) {
  15306. return this;
  15307. }
  15308. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  15309. var subMesh = this.subMeshes[subIndex];
  15310. if (!subMesh.IsGlobal) {
  15311. subMesh.updateBoundingInfo(matrix);
  15312. }
  15313. }
  15314. return this;
  15315. };
  15316. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  15317. // Bounding info
  15318. this._updateBoundingInfo();
  15319. };
  15320. /**
  15321. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  15322. * A mesh is in the frustum if its bounding box intersects the frustum.
  15323. * Boolean returned.
  15324. */
  15325. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  15326. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  15327. };
  15328. /**
  15329. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  15330. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  15331. * Boolean returned.
  15332. */
  15333. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  15334. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  15335. ;
  15336. };
  15337. /**
  15338. * True if the mesh intersects another mesh or a SolidParticle object.
  15339. * 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)
  15340. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  15341. * Returns a boolean.
  15342. */
  15343. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  15344. if (precise === void 0) { precise = false; }
  15345. if (!this._boundingInfo || !mesh._boundingInfo) {
  15346. return false;
  15347. }
  15348. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  15349. return true;
  15350. }
  15351. if (includeDescendants) {
  15352. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  15353. var child = _a[_i];
  15354. if (child.intersectsMesh(mesh, precise, true)) {
  15355. return true;
  15356. }
  15357. }
  15358. }
  15359. return false;
  15360. };
  15361. /**
  15362. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  15363. * Returns a boolean.
  15364. */
  15365. AbstractMesh.prototype.intersectsPoint = function (point) {
  15366. if (!this._boundingInfo) {
  15367. return false;
  15368. }
  15369. return this._boundingInfo.intersectsPoint(point);
  15370. };
  15371. AbstractMesh.prototype.getPhysicsImpostor = function () {
  15372. return this.physicsImpostor;
  15373. };
  15374. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  15375. if (camera === void 0) { camera = null; }
  15376. if (!camera) {
  15377. camera = this.getScene().activeCamera;
  15378. }
  15379. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  15380. };
  15381. /**
  15382. * Returns the distance from the mesh to the active camera.
  15383. * Returns a float.
  15384. */
  15385. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  15386. if (camera === void 0) { camera = null; }
  15387. if (!camera) {
  15388. camera = this.getScene().activeCamera;
  15389. }
  15390. return this.absolutePosition.subtract(camera.position).length();
  15391. };
  15392. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  15393. if (!this.physicsImpostor) {
  15394. return this;
  15395. }
  15396. this.physicsImpostor.applyImpulse(force, contactPoint);
  15397. return this;
  15398. };
  15399. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  15400. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  15401. return this;
  15402. }
  15403. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  15404. mainPivot: pivot1,
  15405. connectedPivot: pivot2,
  15406. nativeParams: options
  15407. });
  15408. return this;
  15409. };
  15410. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  15411. // Collisions
  15412. /**
  15413. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  15414. * Default `false`.
  15415. */
  15416. get: function () {
  15417. return this._checkCollisions;
  15418. },
  15419. set: function (collisionEnabled) {
  15420. this._checkCollisions = collisionEnabled;
  15421. if (this.getScene().workerCollisions) {
  15422. this.getScene().collisionCoordinator.onMeshUpdated(this);
  15423. }
  15424. },
  15425. enumerable: true,
  15426. configurable: true
  15427. });
  15428. Object.defineProperty(AbstractMesh.prototype, "collider", {
  15429. /**
  15430. * Gets Collider object used to compute collisions (not physics)
  15431. */
  15432. get: function () {
  15433. return this._collider;
  15434. },
  15435. enumerable: true,
  15436. configurable: true
  15437. });
  15438. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  15439. var globalPosition = this.getAbsolutePosition();
  15440. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  15441. if (!this._collider) {
  15442. this._collider = new BABYLON.Collider();
  15443. }
  15444. this._collider._radius = this.ellipsoid;
  15445. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  15446. return this;
  15447. };
  15448. // Submeshes octree
  15449. /**
  15450. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  15451. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  15452. * Returns an Octree of submeshes.
  15453. */
  15454. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  15455. if (maxCapacity === void 0) { maxCapacity = 64; }
  15456. if (maxDepth === void 0) { maxDepth = 2; }
  15457. if (!this._submeshesOctree) {
  15458. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  15459. }
  15460. this.computeWorldMatrix(true);
  15461. var boundingInfo = this.getBoundingInfo();
  15462. // Update octree
  15463. var bbox = boundingInfo.boundingBox;
  15464. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  15465. return this._submeshesOctree;
  15466. };
  15467. // Collisions
  15468. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  15469. this._generatePointsArray();
  15470. if (!this._positions) {
  15471. return this;
  15472. }
  15473. // Transformation
  15474. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  15475. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  15476. subMesh._lastColliderWorldVertices = [];
  15477. subMesh._trianglePlanes = [];
  15478. var start = subMesh.verticesStart;
  15479. var end = (subMesh.verticesStart + subMesh.verticesCount);
  15480. for (var i = start; i < end; i++) {
  15481. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  15482. }
  15483. }
  15484. // Collide
  15485. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  15486. if (collider.collisionFound) {
  15487. collider.collidedMesh = this;
  15488. }
  15489. return this;
  15490. };
  15491. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  15492. var subMeshes;
  15493. var len;
  15494. // Octrees
  15495. if (this._submeshesOctree && this.useOctreeForCollisions) {
  15496. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  15497. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  15498. len = intersections.length;
  15499. subMeshes = intersections.data;
  15500. }
  15501. else {
  15502. subMeshes = this.subMeshes;
  15503. len = subMeshes.length;
  15504. }
  15505. for (var index = 0; index < len; index++) {
  15506. var subMesh = subMeshes[index];
  15507. // Bounding test
  15508. if (len > 1 && !subMesh._checkCollision(collider))
  15509. continue;
  15510. this._collideForSubMesh(subMesh, transformMatrix, collider);
  15511. }
  15512. return this;
  15513. };
  15514. AbstractMesh.prototype._checkCollision = function (collider) {
  15515. // Bounding box test
  15516. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  15517. return this;
  15518. // Transformation matrix
  15519. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  15520. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  15521. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  15522. return this;
  15523. };
  15524. // Picking
  15525. AbstractMesh.prototype._generatePointsArray = function () {
  15526. return false;
  15527. };
  15528. /**
  15529. * Checks if the passed Ray intersects with the mesh.
  15530. * Returns an object PickingInfo.
  15531. */
  15532. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  15533. var pickingInfo = new BABYLON.PickingInfo();
  15534. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  15535. return pickingInfo;
  15536. }
  15537. if (!this._generatePointsArray()) {
  15538. return pickingInfo;
  15539. }
  15540. var intersectInfo = null;
  15541. // Octrees
  15542. var subMeshes;
  15543. var len;
  15544. if (this._submeshesOctree && this.useOctreeForPicking) {
  15545. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  15546. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  15547. len = intersections.length;
  15548. subMeshes = intersections.data;
  15549. }
  15550. else {
  15551. subMeshes = this.subMeshes;
  15552. len = subMeshes.length;
  15553. }
  15554. for (var index = 0; index < len; index++) {
  15555. var subMesh = subMeshes[index];
  15556. // Bounding test
  15557. if (len > 1 && !subMesh.canIntersects(ray))
  15558. continue;
  15559. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  15560. if (currentIntersectInfo) {
  15561. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  15562. intersectInfo = currentIntersectInfo;
  15563. intersectInfo.subMeshId = index;
  15564. if (fastCheck) {
  15565. break;
  15566. }
  15567. }
  15568. }
  15569. }
  15570. if (intersectInfo) {
  15571. // Get picked point
  15572. var world = this.getWorldMatrix();
  15573. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  15574. var direction = ray.direction.clone();
  15575. direction = direction.scale(intersectInfo.distance);
  15576. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  15577. var pickedPoint = worldOrigin.add(worldDirection);
  15578. // Return result
  15579. pickingInfo.hit = true;
  15580. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  15581. pickingInfo.pickedPoint = pickedPoint;
  15582. pickingInfo.pickedMesh = this;
  15583. pickingInfo.bu = intersectInfo.bu || 0;
  15584. pickingInfo.bv = intersectInfo.bv || 0;
  15585. pickingInfo.faceId = intersectInfo.faceId;
  15586. pickingInfo.subMeshId = intersectInfo.subMeshId;
  15587. return pickingInfo;
  15588. }
  15589. return pickingInfo;
  15590. };
  15591. /**
  15592. * Clones the mesh, used by the class Mesh.
  15593. * Just returns `null` for an AbstractMesh.
  15594. */
  15595. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15596. return null;
  15597. };
  15598. /**
  15599. * Disposes all the mesh submeshes.
  15600. * Returns the AbstractMesh.
  15601. */
  15602. AbstractMesh.prototype.releaseSubMeshes = function () {
  15603. if (this.subMeshes) {
  15604. while (this.subMeshes.length) {
  15605. this.subMeshes[0].dispose();
  15606. }
  15607. }
  15608. else {
  15609. this.subMeshes = new Array();
  15610. }
  15611. return this;
  15612. };
  15613. /**
  15614. * Disposes the AbstractMesh.
  15615. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  15616. * Returns nothing.
  15617. */
  15618. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  15619. var _this = this;
  15620. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  15621. var index;
  15622. // Action manager
  15623. if (this.actionManager !== undefined && this.actionManager !== null) {
  15624. this.actionManager.dispose();
  15625. this.actionManager = null;
  15626. }
  15627. // Skeleton
  15628. this.skeleton = null;
  15629. // Physics
  15630. if (this.physicsImpostor) {
  15631. this.physicsImpostor.dispose();
  15632. }
  15633. // Intersections in progress
  15634. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  15635. var other = this._intersectionsInProgress[index];
  15636. var pos = other._intersectionsInProgress.indexOf(this);
  15637. other._intersectionsInProgress.splice(pos, 1);
  15638. }
  15639. this._intersectionsInProgress = [];
  15640. // Lights
  15641. var lights = this.getScene().lights;
  15642. lights.forEach(function (light) {
  15643. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  15644. if (meshIndex !== -1) {
  15645. light.includedOnlyMeshes.splice(meshIndex, 1);
  15646. }
  15647. meshIndex = light.excludedMeshes.indexOf(_this);
  15648. if (meshIndex !== -1) {
  15649. light.excludedMeshes.splice(meshIndex, 1);
  15650. }
  15651. // Shadow generators
  15652. var generator = light.getShadowGenerator();
  15653. if (generator) {
  15654. var shadowMap = generator.getShadowMap();
  15655. if (shadowMap && shadowMap.renderList) {
  15656. meshIndex = shadowMap.renderList.indexOf(_this);
  15657. if (meshIndex !== -1) {
  15658. shadowMap.renderList.splice(meshIndex, 1);
  15659. }
  15660. }
  15661. }
  15662. });
  15663. // Edges
  15664. if (this._edgesRenderer) {
  15665. this._edgesRenderer.dispose();
  15666. this._edgesRenderer = null;
  15667. }
  15668. // SubMeshes
  15669. if (this.getClassName() !== "InstancedMesh") {
  15670. this.releaseSubMeshes();
  15671. }
  15672. // Octree
  15673. var sceneOctree = this.getScene().selectionOctree;
  15674. if (sceneOctree !== undefined && sceneOctree !== null) {
  15675. var index = sceneOctree.dynamicContent.indexOf(this);
  15676. if (index !== -1) {
  15677. sceneOctree.dynamicContent.splice(index, 1);
  15678. }
  15679. }
  15680. // Query
  15681. var engine = this.getScene().getEngine();
  15682. if (this._occlusionQuery) {
  15683. this._isOcclusionQueryInProgress = false;
  15684. engine.deleteQuery(this._occlusionQuery);
  15685. this._occlusionQuery = null;
  15686. }
  15687. // Engine
  15688. engine.wipeCaches();
  15689. // Remove from scene
  15690. this.getScene().removeMesh(this);
  15691. if (disposeMaterialAndTextures) {
  15692. if (this.material) {
  15693. this.material.dispose(false, true);
  15694. }
  15695. }
  15696. if (!doNotRecurse) {
  15697. // Particles
  15698. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  15699. if (this.getScene().particleSystems[index].emitter === this) {
  15700. this.getScene().particleSystems[index].dispose();
  15701. index--;
  15702. }
  15703. }
  15704. }
  15705. // facet data
  15706. if (this._facetDataEnabled) {
  15707. this.disableFacetData();
  15708. }
  15709. this.onAfterWorldMatrixUpdateObservable.clear();
  15710. this.onCollideObservable.clear();
  15711. this.onCollisionPositionChangeObservable.clear();
  15712. this._isDisposed = true;
  15713. _super.prototype.dispose.call(this, doNotRecurse);
  15714. };
  15715. /**
  15716. * Adds the passed mesh as a child to the current mesh.
  15717. * Returns the AbstractMesh.
  15718. */
  15719. AbstractMesh.prototype.addChild = function (mesh) {
  15720. mesh.setParent(this);
  15721. return this;
  15722. };
  15723. /**
  15724. * Removes the passed mesh from the current mesh children list.
  15725. * Returns the AbstractMesh.
  15726. */
  15727. AbstractMesh.prototype.removeChild = function (mesh) {
  15728. mesh.setParent(null);
  15729. return this;
  15730. };
  15731. // Facet data
  15732. /**
  15733. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  15734. * Returns the AbstractMesh.
  15735. */
  15736. AbstractMesh.prototype._initFacetData = function () {
  15737. if (!this._facetNormals) {
  15738. this._facetNormals = new Array();
  15739. }
  15740. if (!this._facetPositions) {
  15741. this._facetPositions = new Array();
  15742. }
  15743. if (!this._facetPartitioning) {
  15744. this._facetPartitioning = new Array();
  15745. }
  15746. this._facetNb = (this.getIndices().length / 3) | 0;
  15747. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  15748. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  15749. for (var f = 0; f < this._facetNb; f++) {
  15750. this._facetNormals[f] = BABYLON.Vector3.Zero();
  15751. this._facetPositions[f] = BABYLON.Vector3.Zero();
  15752. }
  15753. this._facetDataEnabled = true;
  15754. return this;
  15755. };
  15756. /**
  15757. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  15758. * This method can be called within the render loop.
  15759. * 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.
  15760. * Returns the AbstractMesh.
  15761. */
  15762. AbstractMesh.prototype.updateFacetData = function () {
  15763. if (!this._facetDataEnabled) {
  15764. this._initFacetData();
  15765. }
  15766. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15767. var indices = this.getIndices();
  15768. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15769. var bInfo = this.getBoundingInfo();
  15770. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  15771. // init arrays, matrix and sort function on first call
  15772. this._facetDepthSortEnabled = true;
  15773. if (indices instanceof Uint16Array) {
  15774. this._depthSortedIndices = new Uint16Array(indices);
  15775. }
  15776. else if (indices instanceof Uint32Array) {
  15777. this._depthSortedIndices = new Uint32Array(indices);
  15778. }
  15779. else {
  15780. var needs32bits = false;
  15781. for (var i = 0; i < indices.length; i++) {
  15782. if (indices[i] > 65535) {
  15783. needs32bits = true;
  15784. break;
  15785. }
  15786. }
  15787. if (needs32bits) {
  15788. this._depthSortedIndices = new Uint32Array(indices);
  15789. }
  15790. else {
  15791. this._depthSortedIndices = new Uint16Array(indices);
  15792. }
  15793. }
  15794. this._facetDepthSortFunction = function (f1, f2) {
  15795. return (f2.sqDistance - f1.sqDistance);
  15796. };
  15797. if (!this._facetDepthSortFrom) {
  15798. var camera = this.getScene().activeCamera;
  15799. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  15800. }
  15801. this._depthSortedFacets = [];
  15802. for (var f = 0; f < this._facetNb; f++) {
  15803. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  15804. this._depthSortedFacets.push(depthSortedFacet);
  15805. }
  15806. this._invertedMatrix = BABYLON.Matrix.Identity();
  15807. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  15808. }
  15809. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  15810. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  15811. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  15812. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  15813. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  15814. this._subDiv.max = this._partitioningSubdivisions;
  15815. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  15816. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  15817. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  15818. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  15819. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  15820. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  15821. // set the parameters for ComputeNormals()
  15822. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  15823. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  15824. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  15825. this._facetParameters.bInfo = bInfo;
  15826. this._facetParameters.bbSize = this._bbSize;
  15827. this._facetParameters.subDiv = this._subDiv;
  15828. this._facetParameters.ratio = this.partitioningBBoxRatio;
  15829. this._facetParameters.depthSort = this._facetDepthSort;
  15830. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  15831. this.computeWorldMatrix(true);
  15832. this._worldMatrix.invertToRef(this._invertedMatrix);
  15833. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  15834. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  15835. }
  15836. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  15837. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  15838. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  15839. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  15840. var l = (this._depthSortedIndices.length / 3) | 0;
  15841. for (var f = 0; f < l; f++) {
  15842. var sind = this._depthSortedFacets[f].ind;
  15843. this._depthSortedIndices[f * 3] = indices[sind];
  15844. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  15845. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  15846. }
  15847. this.updateIndices(this._depthSortedIndices);
  15848. }
  15849. return this;
  15850. };
  15851. /**
  15852. * Returns the facetLocalNormals array.
  15853. * The normals are expressed in the mesh local space.
  15854. */
  15855. AbstractMesh.prototype.getFacetLocalNormals = function () {
  15856. if (!this._facetNormals) {
  15857. this.updateFacetData();
  15858. }
  15859. return this._facetNormals;
  15860. };
  15861. /**
  15862. * Returns the facetLocalPositions array.
  15863. * The facet positions are expressed in the mesh local space.
  15864. */
  15865. AbstractMesh.prototype.getFacetLocalPositions = function () {
  15866. if (!this._facetPositions) {
  15867. this.updateFacetData();
  15868. }
  15869. return this._facetPositions;
  15870. };
  15871. /**
  15872. * Returns the facetLocalPartioning array.
  15873. */
  15874. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  15875. if (!this._facetPartitioning) {
  15876. this.updateFacetData();
  15877. }
  15878. return this._facetPartitioning;
  15879. };
  15880. /**
  15881. * Returns the i-th facet position in the world system.
  15882. * This method allocates a new Vector3 per call.
  15883. */
  15884. AbstractMesh.prototype.getFacetPosition = function (i) {
  15885. var pos = BABYLON.Vector3.Zero();
  15886. this.getFacetPositionToRef(i, pos);
  15887. return pos;
  15888. };
  15889. /**
  15890. * Sets the reference Vector3 with the i-th facet position in the world system.
  15891. * Returns the AbstractMesh.
  15892. */
  15893. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  15894. var localPos = (this.getFacetLocalPositions())[i];
  15895. var world = this.getWorldMatrix();
  15896. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  15897. return this;
  15898. };
  15899. /**
  15900. * Returns the i-th facet normal in the world system.
  15901. * This method allocates a new Vector3 per call.
  15902. */
  15903. AbstractMesh.prototype.getFacetNormal = function (i) {
  15904. var norm = BABYLON.Vector3.Zero();
  15905. this.getFacetNormalToRef(i, norm);
  15906. return norm;
  15907. };
  15908. /**
  15909. * Sets the reference Vector3 with the i-th facet normal in the world system.
  15910. * Returns the AbstractMesh.
  15911. */
  15912. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  15913. var localNorm = (this.getFacetLocalNormals())[i];
  15914. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  15915. return this;
  15916. };
  15917. /**
  15918. * 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).
  15919. */
  15920. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  15921. var bInfo = this.getBoundingInfo();
  15922. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  15923. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  15924. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  15925. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  15926. return null;
  15927. }
  15928. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  15929. };
  15930. /**
  15931. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  15932. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  15933. * 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.
  15934. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  15935. * 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.
  15936. */
  15937. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  15938. if (checkFace === void 0) { checkFace = false; }
  15939. if (facing === void 0) { facing = true; }
  15940. var world = this.getWorldMatrix();
  15941. var invMat = BABYLON.Tmp.Matrix[5];
  15942. world.invertToRef(invMat);
  15943. var invVect = BABYLON.Tmp.Vector3[8];
  15944. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  15945. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  15946. if (projected) {
  15947. // tranform the local computed projected vector to world coordinates
  15948. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  15949. }
  15950. return closest;
  15951. };
  15952. /**
  15953. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  15954. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  15955. * 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.
  15956. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  15957. * 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.
  15958. */
  15959. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  15960. if (checkFace === void 0) { checkFace = false; }
  15961. if (facing === void 0) { facing = true; }
  15962. var closest = null;
  15963. var tmpx = 0.0;
  15964. var tmpy = 0.0;
  15965. var tmpz = 0.0;
  15966. var d = 0.0; // tmp dot facet normal * facet position
  15967. var t0 = 0.0;
  15968. var projx = 0.0;
  15969. var projy = 0.0;
  15970. var projz = 0.0;
  15971. // Get all the facets in the same partitioning block than (x, y, z)
  15972. var facetPositions = this.getFacetLocalPositions();
  15973. var facetNormals = this.getFacetLocalNormals();
  15974. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  15975. if (!facetsInBlock) {
  15976. return null;
  15977. }
  15978. // Get the closest facet to (x, y, z)
  15979. var shortest = Number.MAX_VALUE; // init distance vars
  15980. var tmpDistance = shortest;
  15981. var fib; // current facet in the block
  15982. var norm; // current facet normal
  15983. var p0; // current facet barycenter position
  15984. // loop on all the facets in the current partitioning block
  15985. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  15986. fib = facetsInBlock[idx];
  15987. norm = facetNormals[fib];
  15988. p0 = facetPositions[fib];
  15989. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  15990. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  15991. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  15992. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  15993. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  15994. projx = x + norm.x * t0;
  15995. projy = y + norm.y * t0;
  15996. projz = z + norm.z * t0;
  15997. tmpx = projx - x;
  15998. tmpy = projy - y;
  15999. tmpz = projz - z;
  16000. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  16001. if (tmpDistance < shortest) {
  16002. shortest = tmpDistance;
  16003. closest = fib;
  16004. if (projected) {
  16005. projected.x = projx;
  16006. projected.y = projy;
  16007. projected.z = projz;
  16008. }
  16009. }
  16010. }
  16011. }
  16012. return closest;
  16013. };
  16014. /**
  16015. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  16016. */
  16017. AbstractMesh.prototype.getFacetDataParameters = function () {
  16018. return this._facetParameters;
  16019. };
  16020. /**
  16021. * Disables the feature FacetData and frees the related memory.
  16022. * Returns the AbstractMesh.
  16023. */
  16024. AbstractMesh.prototype.disableFacetData = function () {
  16025. if (this._facetDataEnabled) {
  16026. this._facetDataEnabled = false;
  16027. this._facetPositions = new Array();
  16028. this._facetNormals = new Array();
  16029. this._facetPartitioning = new Array();
  16030. this._facetParameters = null;
  16031. this._depthSortedIndices = new Uint32Array(0);
  16032. }
  16033. return this;
  16034. };
  16035. /**
  16036. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  16037. * Returns the mesh.
  16038. */
  16039. AbstractMesh.prototype.updateIndices = function (indices) {
  16040. return this;
  16041. };
  16042. /**
  16043. * The mesh Geometry. Actually used by the Mesh object.
  16044. * Returns a blank geometry object.
  16045. */
  16046. /**
  16047. * Creates new normals data for the mesh.
  16048. * @param updatable.
  16049. */
  16050. AbstractMesh.prototype.createNormals = function (updatable) {
  16051. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16052. var indices = this.getIndices();
  16053. var normals;
  16054. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16055. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16056. }
  16057. else {
  16058. normals = [];
  16059. }
  16060. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  16061. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  16062. };
  16063. /**
  16064. * Align the mesh with a normal.
  16065. * Returns the mesh.
  16066. */
  16067. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  16068. if (!upDirection) {
  16069. upDirection = BABYLON.Axis.Y;
  16070. }
  16071. var axisX = BABYLON.Tmp.Vector3[0];
  16072. var axisZ = BABYLON.Tmp.Vector3[1];
  16073. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  16074. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  16075. if (this.rotationQuaternion) {
  16076. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  16077. }
  16078. else {
  16079. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  16080. }
  16081. return this;
  16082. };
  16083. AbstractMesh.prototype.checkOcclusionQuery = function () {
  16084. var engine = this.getEngine();
  16085. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  16086. this._isOccluded = false;
  16087. return;
  16088. }
  16089. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  16090. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  16091. if (isOcclusionQueryAvailable) {
  16092. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  16093. this._isOcclusionQueryInProgress = false;
  16094. this._occlusionInternalRetryCounter = 0;
  16095. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  16096. }
  16097. else {
  16098. this._occlusionInternalRetryCounter++;
  16099. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  16100. this._isOcclusionQueryInProgress = false;
  16101. this._occlusionInternalRetryCounter = 0;
  16102. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  16103. // if strict continue the last state of the object.
  16104. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  16105. }
  16106. else {
  16107. return;
  16108. }
  16109. }
  16110. }
  16111. var scene = this.getScene();
  16112. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  16113. if (!this._occlusionQuery) {
  16114. this._occlusionQuery = engine.createQuery();
  16115. }
  16116. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  16117. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  16118. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  16119. this._isOcclusionQueryInProgress = true;
  16120. };
  16121. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  16122. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  16123. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  16124. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  16125. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  16126. return AbstractMesh;
  16127. }(BABYLON.TransformNode));
  16128. BABYLON.AbstractMesh = AbstractMesh;
  16129. })(BABYLON || (BABYLON = {}));
  16130. //# sourceMappingURL=babylon.abstractMesh.js.map
  16131. var BABYLON;
  16132. (function (BABYLON) {
  16133. var Light = /** @class */ (function (_super) {
  16134. __extends(Light, _super);
  16135. /**
  16136. * Creates a Light object in the scene.
  16137. * Documentation : http://doc.babylonjs.com/tutorials/lights
  16138. */
  16139. function Light(name, scene) {
  16140. var _this = _super.call(this, name, scene) || this;
  16141. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  16142. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  16143. _this.intensity = 1.0;
  16144. _this.range = Number.MAX_VALUE;
  16145. /**
  16146. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  16147. * of light.
  16148. */
  16149. _this._photometricScale = 1.0;
  16150. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  16151. _this._radius = 0.00001;
  16152. _this.renderPriority = 0;
  16153. /**
  16154. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  16155. * the current shadow generator.
  16156. */
  16157. _this.shadowEnabled = true;
  16158. _this._excludeWithLayerMask = 0;
  16159. _this._includeOnlyWithLayerMask = 0;
  16160. _this._lightmapMode = 0;
  16161. _this._excludedMeshesIds = new Array();
  16162. _this._includedOnlyMeshesIds = new Array();
  16163. _this.getScene().addLight(_this);
  16164. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  16165. _this._buildUniformLayout();
  16166. _this.includedOnlyMeshes = new Array();
  16167. _this.excludedMeshes = new Array();
  16168. _this._resyncMeshes();
  16169. return _this;
  16170. }
  16171. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  16172. /**
  16173. * If every light affecting the material is in this lightmapMode,
  16174. * material.lightmapTexture adds or multiplies
  16175. * (depends on material.useLightmapAsShadowmap)
  16176. * after every other light calculations.
  16177. */
  16178. get: function () {
  16179. return Light._LIGHTMAP_DEFAULT;
  16180. },
  16181. enumerable: true,
  16182. configurable: true
  16183. });
  16184. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  16185. /**
  16186. * material.lightmapTexture as only diffuse lighting from this light
  16187. * adds pnly specular lighting from this light
  16188. * adds dynamic shadows
  16189. */
  16190. get: function () {
  16191. return Light._LIGHTMAP_SPECULAR;
  16192. },
  16193. enumerable: true,
  16194. configurable: true
  16195. });
  16196. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  16197. /**
  16198. * material.lightmapTexture as only lighting
  16199. * no light calculation from this light
  16200. * only adds dynamic shadows from this light
  16201. */
  16202. get: function () {
  16203. return Light._LIGHTMAP_SHADOWSONLY;
  16204. },
  16205. enumerable: true,
  16206. configurable: true
  16207. });
  16208. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  16209. /**
  16210. * Each light type uses the default quantity according to its type:
  16211. * point/spot lights use luminous intensity
  16212. * directional lights use illuminance
  16213. */
  16214. get: function () {
  16215. return Light._INTENSITYMODE_AUTOMATIC;
  16216. },
  16217. enumerable: true,
  16218. configurable: true
  16219. });
  16220. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  16221. /**
  16222. * lumen (lm)
  16223. */
  16224. get: function () {
  16225. return Light._INTENSITYMODE_LUMINOUSPOWER;
  16226. },
  16227. enumerable: true,
  16228. configurable: true
  16229. });
  16230. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  16231. /**
  16232. * candela (lm/sr)
  16233. */
  16234. get: function () {
  16235. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  16236. },
  16237. enumerable: true,
  16238. configurable: true
  16239. });
  16240. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  16241. /**
  16242. * lux (lm/m^2)
  16243. */
  16244. get: function () {
  16245. return Light._INTENSITYMODE_ILLUMINANCE;
  16246. },
  16247. enumerable: true,
  16248. configurable: true
  16249. });
  16250. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  16251. /**
  16252. * nit (cd/m^2)
  16253. */
  16254. get: function () {
  16255. return Light._INTENSITYMODE_LUMINANCE;
  16256. },
  16257. enumerable: true,
  16258. configurable: true
  16259. });
  16260. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  16261. /**
  16262. * Light type const id of the point light.
  16263. */
  16264. get: function () {
  16265. return Light._LIGHTTYPEID_POINTLIGHT;
  16266. },
  16267. enumerable: true,
  16268. configurable: true
  16269. });
  16270. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  16271. /**
  16272. * Light type const id of the directional light.
  16273. */
  16274. get: function () {
  16275. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  16276. },
  16277. enumerable: true,
  16278. configurable: true
  16279. });
  16280. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  16281. /**
  16282. * Light type const id of the spot light.
  16283. */
  16284. get: function () {
  16285. return Light._LIGHTTYPEID_SPOTLIGHT;
  16286. },
  16287. enumerable: true,
  16288. configurable: true
  16289. });
  16290. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  16291. /**
  16292. * Light type const id of the hemispheric light.
  16293. */
  16294. get: function () {
  16295. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  16296. },
  16297. enumerable: true,
  16298. configurable: true
  16299. });
  16300. Object.defineProperty(Light.prototype, "intensityMode", {
  16301. /**
  16302. * Gets the photometric scale used to interpret the intensity.
  16303. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  16304. */
  16305. get: function () {
  16306. return this._intensityMode;
  16307. },
  16308. /**
  16309. * Sets the photometric scale used to interpret the intensity.
  16310. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  16311. */
  16312. set: function (value) {
  16313. this._intensityMode = value;
  16314. this._computePhotometricScale();
  16315. },
  16316. enumerable: true,
  16317. configurable: true
  16318. });
  16319. ;
  16320. ;
  16321. Object.defineProperty(Light.prototype, "radius", {
  16322. /**
  16323. * Gets the light radius used by PBR Materials to simulate soft area lights.
  16324. */
  16325. get: function () {
  16326. return this._radius;
  16327. },
  16328. /**
  16329. * sets the light radius used by PBR Materials to simulate soft area lights.
  16330. */
  16331. set: function (value) {
  16332. this._radius = value;
  16333. this._computePhotometricScale();
  16334. },
  16335. enumerable: true,
  16336. configurable: true
  16337. });
  16338. ;
  16339. ;
  16340. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  16341. get: function () {
  16342. return this._includedOnlyMeshes;
  16343. },
  16344. set: function (value) {
  16345. this._includedOnlyMeshes = value;
  16346. this._hookArrayForIncludedOnly(value);
  16347. },
  16348. enumerable: true,
  16349. configurable: true
  16350. });
  16351. Object.defineProperty(Light.prototype, "excludedMeshes", {
  16352. get: function () {
  16353. return this._excludedMeshes;
  16354. },
  16355. set: function (value) {
  16356. this._excludedMeshes = value;
  16357. this._hookArrayForExcluded(value);
  16358. },
  16359. enumerable: true,
  16360. configurable: true
  16361. });
  16362. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  16363. get: function () {
  16364. return this._excludeWithLayerMask;
  16365. },
  16366. set: function (value) {
  16367. this._excludeWithLayerMask = value;
  16368. this._resyncMeshes();
  16369. },
  16370. enumerable: true,
  16371. configurable: true
  16372. });
  16373. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  16374. get: function () {
  16375. return this._includeOnlyWithLayerMask;
  16376. },
  16377. set: function (value) {
  16378. this._includeOnlyWithLayerMask = value;
  16379. this._resyncMeshes();
  16380. },
  16381. enumerable: true,
  16382. configurable: true
  16383. });
  16384. Object.defineProperty(Light.prototype, "lightmapMode", {
  16385. get: function () {
  16386. return this._lightmapMode;
  16387. },
  16388. set: function (value) {
  16389. if (this._lightmapMode === value) {
  16390. return;
  16391. }
  16392. this._lightmapMode = value;
  16393. this._markMeshesAsLightDirty();
  16394. },
  16395. enumerable: true,
  16396. configurable: true
  16397. });
  16398. Light.prototype._buildUniformLayout = function () {
  16399. // Overridden
  16400. };
  16401. /**
  16402. * Returns the string "Light".
  16403. */
  16404. Light.prototype.getClassName = function () {
  16405. return "Light";
  16406. };
  16407. /**
  16408. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  16409. */
  16410. Light.prototype.toString = function (fullDetails) {
  16411. var ret = "Name: " + this.name;
  16412. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  16413. if (this.animations) {
  16414. for (var i = 0; i < this.animations.length; i++) {
  16415. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  16416. }
  16417. }
  16418. if (fullDetails) {
  16419. }
  16420. return ret;
  16421. };
  16422. /**
  16423. * Set the enabled state of this node.
  16424. * @param {boolean} value - the new enabled state
  16425. * @see isEnabled
  16426. */
  16427. Light.prototype.setEnabled = function (value) {
  16428. _super.prototype.setEnabled.call(this, value);
  16429. this._resyncMeshes();
  16430. };
  16431. /**
  16432. * Returns the Light associated shadow generator.
  16433. */
  16434. Light.prototype.getShadowGenerator = function () {
  16435. return this._shadowGenerator;
  16436. };
  16437. /**
  16438. * Returns a Vector3, the absolute light position in the World.
  16439. */
  16440. Light.prototype.getAbsolutePosition = function () {
  16441. return BABYLON.Vector3.Zero();
  16442. };
  16443. Light.prototype.transferToEffect = function (effect, lightIndex) {
  16444. };
  16445. Light.prototype._getWorldMatrix = function () {
  16446. return BABYLON.Matrix.Identity();
  16447. };
  16448. /**
  16449. * Boolean : True if the light will affect the passed mesh.
  16450. */
  16451. Light.prototype.canAffectMesh = function (mesh) {
  16452. if (!mesh) {
  16453. return true;
  16454. }
  16455. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  16456. return false;
  16457. }
  16458. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  16459. return false;
  16460. }
  16461. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  16462. return false;
  16463. }
  16464. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  16465. return false;
  16466. }
  16467. return true;
  16468. };
  16469. /**
  16470. * Returns the light World matrix.
  16471. */
  16472. Light.prototype.getWorldMatrix = function () {
  16473. this._currentRenderId = this.getScene().getRenderId();
  16474. var worldMatrix = this._getWorldMatrix();
  16475. if (this.parent && this.parent.getWorldMatrix) {
  16476. if (!this._parentedWorldMatrix) {
  16477. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  16478. }
  16479. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  16480. this._markSyncedWithParent();
  16481. return this._parentedWorldMatrix;
  16482. }
  16483. return worldMatrix;
  16484. };
  16485. /**
  16486. * Sort function to order lights for rendering.
  16487. * @param a First Light object to compare to second.
  16488. * @param b Second Light object to compare first.
  16489. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  16490. */
  16491. Light.compareLightsPriority = function (a, b) {
  16492. //shadow-casting lights have priority over non-shadow-casting lights
  16493. //the renderPrioirty is a secondary sort criterion
  16494. if (a.shadowEnabled !== b.shadowEnabled) {
  16495. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  16496. }
  16497. return b.renderPriority - a.renderPriority;
  16498. };
  16499. /**
  16500. * Disposes the light.
  16501. */
  16502. Light.prototype.dispose = function () {
  16503. if (this._shadowGenerator) {
  16504. this._shadowGenerator.dispose();
  16505. this._shadowGenerator = null;
  16506. }
  16507. // Animations
  16508. this.getScene().stopAnimation(this);
  16509. this._uniformBuffer.dispose();
  16510. // Remove from scene
  16511. this.getScene().removeLight(this);
  16512. _super.prototype.dispose.call(this);
  16513. };
  16514. /**
  16515. * Returns the light type ID (integer).
  16516. */
  16517. Light.prototype.getTypeID = function () {
  16518. return 0;
  16519. };
  16520. /**
  16521. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  16522. */
  16523. Light.prototype.getScaledIntensity = function () {
  16524. return this._photometricScale * this.intensity;
  16525. };
  16526. /**
  16527. * Returns a new Light object, named "name", from the current one.
  16528. */
  16529. Light.prototype.clone = function (name) {
  16530. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  16531. if (!constructor) {
  16532. return null;
  16533. }
  16534. return BABYLON.SerializationHelper.Clone(constructor, this);
  16535. };
  16536. /**
  16537. * Serializes the current light into a Serialization object.
  16538. * Returns the serialized object.
  16539. */
  16540. Light.prototype.serialize = function () {
  16541. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  16542. // Type
  16543. serializationObject.type = this.getTypeID();
  16544. // Parent
  16545. if (this.parent) {
  16546. serializationObject.parentId = this.parent.id;
  16547. }
  16548. // Inclusion / exclusions
  16549. if (this.excludedMeshes.length > 0) {
  16550. serializationObject.excludedMeshesIds = [];
  16551. this.excludedMeshes.forEach(function (mesh) {
  16552. serializationObject.excludedMeshesIds.push(mesh.id);
  16553. });
  16554. }
  16555. if (this.includedOnlyMeshes.length > 0) {
  16556. serializationObject.includedOnlyMeshesIds = [];
  16557. this.includedOnlyMeshes.forEach(function (mesh) {
  16558. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  16559. });
  16560. }
  16561. // Animations
  16562. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  16563. serializationObject.ranges = this.serializeAnimationRanges();
  16564. return serializationObject;
  16565. };
  16566. /**
  16567. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  16568. * This new light is named "name" and added to the passed scene.
  16569. */
  16570. Light.GetConstructorFromName = function (type, name, scene) {
  16571. switch (type) {
  16572. case 0:
  16573. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  16574. case 1:
  16575. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  16576. case 2:
  16577. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  16578. case 3:
  16579. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  16580. }
  16581. return null;
  16582. };
  16583. /**
  16584. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  16585. */
  16586. Light.Parse = function (parsedLight, scene) {
  16587. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  16588. if (!constructor) {
  16589. return null;
  16590. }
  16591. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  16592. // Inclusion / exclusions
  16593. if (parsedLight.excludedMeshesIds) {
  16594. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  16595. }
  16596. if (parsedLight.includedOnlyMeshesIds) {
  16597. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  16598. }
  16599. // Parent
  16600. if (parsedLight.parentId) {
  16601. light._waitingParentId = parsedLight.parentId;
  16602. }
  16603. // Animations
  16604. if (parsedLight.animations) {
  16605. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  16606. var parsedAnimation = parsedLight.animations[animationIndex];
  16607. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16608. }
  16609. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  16610. }
  16611. if (parsedLight.autoAnimate) {
  16612. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  16613. }
  16614. return light;
  16615. };
  16616. Light.prototype._hookArrayForExcluded = function (array) {
  16617. var _this = this;
  16618. var oldPush = array.push;
  16619. array.push = function () {
  16620. var items = [];
  16621. for (var _i = 0; _i < arguments.length; _i++) {
  16622. items[_i] = arguments[_i];
  16623. }
  16624. var result = oldPush.apply(array, items);
  16625. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  16626. var item = items_1[_a];
  16627. item._resyncLighSource(_this);
  16628. }
  16629. return result;
  16630. };
  16631. var oldSplice = array.splice;
  16632. array.splice = function (index, deleteCount) {
  16633. var deleted = oldSplice.apply(array, [index, deleteCount]);
  16634. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  16635. var item = deleted_1[_i];
  16636. item._resyncLighSource(_this);
  16637. }
  16638. return deleted;
  16639. };
  16640. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  16641. var item = array_1[_i];
  16642. item._resyncLighSource(this);
  16643. }
  16644. };
  16645. Light.prototype._hookArrayForIncludedOnly = function (array) {
  16646. var _this = this;
  16647. var oldPush = array.push;
  16648. array.push = function () {
  16649. var items = [];
  16650. for (var _i = 0; _i < arguments.length; _i++) {
  16651. items[_i] = arguments[_i];
  16652. }
  16653. var result = oldPush.apply(array, items);
  16654. _this._resyncMeshes();
  16655. return result;
  16656. };
  16657. var oldSplice = array.splice;
  16658. array.splice = function (index, deleteCount) {
  16659. var deleted = oldSplice.apply(array, [index, deleteCount]);
  16660. _this._resyncMeshes();
  16661. return deleted;
  16662. };
  16663. this._resyncMeshes();
  16664. };
  16665. Light.prototype._resyncMeshes = function () {
  16666. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  16667. var mesh = _a[_i];
  16668. mesh._resyncLighSource(this);
  16669. }
  16670. };
  16671. Light.prototype._markMeshesAsLightDirty = function () {
  16672. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  16673. var mesh = _a[_i];
  16674. if (mesh._lightSources.indexOf(this) !== -1) {
  16675. mesh._markSubMeshesAsLightDirty();
  16676. }
  16677. }
  16678. };
  16679. /**
  16680. * Recomputes the cached photometric scale if needed.
  16681. */
  16682. Light.prototype._computePhotometricScale = function () {
  16683. this._photometricScale = this._getPhotometricScale();
  16684. this.getScene().resetCachedMaterial();
  16685. };
  16686. /**
  16687. * Returns the Photometric Scale according to the light type and intensity mode.
  16688. */
  16689. Light.prototype._getPhotometricScale = function () {
  16690. var photometricScale = 0.0;
  16691. var lightTypeID = this.getTypeID();
  16692. //get photometric mode
  16693. var photometricMode = this.intensityMode;
  16694. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  16695. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  16696. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  16697. }
  16698. else {
  16699. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  16700. }
  16701. }
  16702. //compute photometric scale
  16703. switch (lightTypeID) {
  16704. case Light.LIGHTTYPEID_POINTLIGHT:
  16705. case Light.LIGHTTYPEID_SPOTLIGHT:
  16706. switch (photometricMode) {
  16707. case Light.INTENSITYMODE_LUMINOUSPOWER:
  16708. photometricScale = 1.0 / (4.0 * Math.PI);
  16709. break;
  16710. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  16711. photometricScale = 1.0;
  16712. break;
  16713. case Light.INTENSITYMODE_LUMINANCE:
  16714. photometricScale = this.radius * this.radius;
  16715. break;
  16716. }
  16717. break;
  16718. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  16719. switch (photometricMode) {
  16720. case Light.INTENSITYMODE_ILLUMINANCE:
  16721. photometricScale = 1.0;
  16722. break;
  16723. case Light.INTENSITYMODE_LUMINANCE:
  16724. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  16725. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  16726. var apexAngleRadians = this.radius;
  16727. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  16728. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  16729. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  16730. photometricScale = solidAngle;
  16731. break;
  16732. }
  16733. break;
  16734. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  16735. // No fall off in hemisperic light.
  16736. photometricScale = 1.0;
  16737. break;
  16738. }
  16739. return photometricScale;
  16740. };
  16741. Light.prototype._reorderLightsInScene = function () {
  16742. var scene = this.getScene();
  16743. if (this._renderPriority != 0) {
  16744. scene.requireLightSorting = true;
  16745. }
  16746. this.getScene().sortLightsByPriority();
  16747. };
  16748. //lightmapMode Consts
  16749. Light._LIGHTMAP_DEFAULT = 0;
  16750. Light._LIGHTMAP_SPECULAR = 1;
  16751. Light._LIGHTMAP_SHADOWSONLY = 2;
  16752. // Intensity Mode Consts
  16753. Light._INTENSITYMODE_AUTOMATIC = 0;
  16754. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  16755. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  16756. Light._INTENSITYMODE_ILLUMINANCE = 3;
  16757. Light._INTENSITYMODE_LUMINANCE = 4;
  16758. // Light types ids const.
  16759. Light._LIGHTTYPEID_POINTLIGHT = 0;
  16760. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  16761. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  16762. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  16763. __decorate([
  16764. BABYLON.serializeAsColor3()
  16765. ], Light.prototype, "diffuse", void 0);
  16766. __decorate([
  16767. BABYLON.serializeAsColor3()
  16768. ], Light.prototype, "specular", void 0);
  16769. __decorate([
  16770. BABYLON.serialize()
  16771. ], Light.prototype, "intensity", void 0);
  16772. __decorate([
  16773. BABYLON.serialize()
  16774. ], Light.prototype, "range", void 0);
  16775. __decorate([
  16776. BABYLON.serialize()
  16777. ], Light.prototype, "intensityMode", null);
  16778. __decorate([
  16779. BABYLON.serialize()
  16780. ], Light.prototype, "radius", null);
  16781. __decorate([
  16782. BABYLON.serialize()
  16783. ], Light.prototype, "_renderPriority", void 0);
  16784. __decorate([
  16785. BABYLON.expandToProperty("_reorderLightsInScene")
  16786. ], Light.prototype, "renderPriority", void 0);
  16787. __decorate([
  16788. BABYLON.serialize()
  16789. ], Light.prototype, "shadowEnabled", void 0);
  16790. __decorate([
  16791. BABYLON.serialize("excludeWithLayerMask")
  16792. ], Light.prototype, "_excludeWithLayerMask", void 0);
  16793. __decorate([
  16794. BABYLON.serialize("includeOnlyWithLayerMask")
  16795. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  16796. __decorate([
  16797. BABYLON.serialize("lightmapMode")
  16798. ], Light.prototype, "_lightmapMode", void 0);
  16799. return Light;
  16800. }(BABYLON.Node));
  16801. BABYLON.Light = Light;
  16802. })(BABYLON || (BABYLON = {}));
  16803. //# sourceMappingURL=babylon.light.js.map
  16804. var BABYLON;
  16805. (function (BABYLON) {
  16806. var Camera = /** @class */ (function (_super) {
  16807. __extends(Camera, _super);
  16808. function Camera(name, position, scene) {
  16809. var _this = _super.call(this, name, scene) || this;
  16810. _this.upVector = BABYLON.Vector3.Up();
  16811. _this.orthoLeft = null;
  16812. _this.orthoRight = null;
  16813. _this.orthoBottom = null;
  16814. _this.orthoTop = null;
  16815. _this.fov = 0.8;
  16816. _this.minZ = 1;
  16817. _this.maxZ = 10000.0;
  16818. _this.inertia = 0.9;
  16819. _this.mode = Camera.PERSPECTIVE_CAMERA;
  16820. _this.isIntermediate = false;
  16821. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  16822. _this.layerMask = 0x0FFFFFFF;
  16823. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  16824. // Camera rig members
  16825. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  16826. _this._rigCameras = new Array();
  16827. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  16828. _this._skipRendering = false;
  16829. _this.customRenderTargets = new Array();
  16830. // Observables
  16831. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  16832. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  16833. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  16834. _this.onRestoreStateObservable = new BABYLON.Observable();
  16835. // Cache
  16836. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  16837. _this._projectionMatrix = new BABYLON.Matrix();
  16838. _this._doNotComputeProjectionMatrix = false;
  16839. _this._postProcesses = new Array();
  16840. _this._transformMatrix = BABYLON.Matrix.Zero();
  16841. _this._activeMeshes = new BABYLON.SmartArray(256);
  16842. _this._globalPosition = BABYLON.Vector3.Zero();
  16843. _this._refreshFrustumPlanes = true;
  16844. _this.getScene().addCamera(_this);
  16845. if (!_this.getScene().activeCamera) {
  16846. _this.getScene().activeCamera = _this;
  16847. }
  16848. _this.position = position;
  16849. return _this;
  16850. }
  16851. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  16852. get: function () {
  16853. return Camera._PERSPECTIVE_CAMERA;
  16854. },
  16855. enumerable: true,
  16856. configurable: true
  16857. });
  16858. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  16859. get: function () {
  16860. return Camera._ORTHOGRAPHIC_CAMERA;
  16861. },
  16862. enumerable: true,
  16863. configurable: true
  16864. });
  16865. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  16866. get: function () {
  16867. return Camera._FOVMODE_VERTICAL_FIXED;
  16868. },
  16869. enumerable: true,
  16870. configurable: true
  16871. });
  16872. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  16873. get: function () {
  16874. return Camera._FOVMODE_HORIZONTAL_FIXED;
  16875. },
  16876. enumerable: true,
  16877. configurable: true
  16878. });
  16879. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  16880. get: function () {
  16881. return Camera._RIG_MODE_NONE;
  16882. },
  16883. enumerable: true,
  16884. configurable: true
  16885. });
  16886. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  16887. get: function () {
  16888. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  16889. },
  16890. enumerable: true,
  16891. configurable: true
  16892. });
  16893. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  16894. get: function () {
  16895. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  16896. },
  16897. enumerable: true,
  16898. configurable: true
  16899. });
  16900. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  16901. get: function () {
  16902. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  16903. },
  16904. enumerable: true,
  16905. configurable: true
  16906. });
  16907. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  16908. get: function () {
  16909. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  16910. },
  16911. enumerable: true,
  16912. configurable: true
  16913. });
  16914. Object.defineProperty(Camera, "RIG_MODE_VR", {
  16915. get: function () {
  16916. return Camera._RIG_MODE_VR;
  16917. },
  16918. enumerable: true,
  16919. configurable: true
  16920. });
  16921. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  16922. get: function () {
  16923. return Camera._RIG_MODE_WEBVR;
  16924. },
  16925. enumerable: true,
  16926. configurable: true
  16927. });
  16928. /**
  16929. * Store current camera state (fov, position, etc..)
  16930. */
  16931. Camera.prototype.storeState = function () {
  16932. this._stateStored = true;
  16933. this._storedFov = this.fov;
  16934. return this;
  16935. };
  16936. /**
  16937. * Restores the camera state values if it has been stored. You must call storeState() first
  16938. */
  16939. Camera.prototype._restoreStateValues = function () {
  16940. if (!this._stateStored) {
  16941. return false;
  16942. }
  16943. this.fov = this._storedFov;
  16944. return true;
  16945. };
  16946. /**
  16947. * Restored camera state. You must call storeState() first
  16948. */
  16949. Camera.prototype.restoreState = function () {
  16950. if (this._restoreStateValues()) {
  16951. this.onRestoreStateObservable.notifyObservers(this);
  16952. return true;
  16953. }
  16954. return false;
  16955. };
  16956. Camera.prototype.getClassName = function () {
  16957. return "Camera";
  16958. };
  16959. /**
  16960. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  16961. */
  16962. Camera.prototype.toString = function (fullDetails) {
  16963. var ret = "Name: " + this.name;
  16964. ret += ", type: " + this.getClassName();
  16965. if (this.animations) {
  16966. for (var i = 0; i < this.animations.length; i++) {
  16967. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  16968. }
  16969. }
  16970. if (fullDetails) {
  16971. }
  16972. return ret;
  16973. };
  16974. Object.defineProperty(Camera.prototype, "globalPosition", {
  16975. get: function () {
  16976. return this._globalPosition;
  16977. },
  16978. enumerable: true,
  16979. configurable: true
  16980. });
  16981. Camera.prototype.getActiveMeshes = function () {
  16982. return this._activeMeshes;
  16983. };
  16984. Camera.prototype.isActiveMesh = function (mesh) {
  16985. return (this._activeMeshes.indexOf(mesh) !== -1);
  16986. };
  16987. //Cache
  16988. Camera.prototype._initCache = function () {
  16989. _super.prototype._initCache.call(this);
  16990. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16991. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16992. this._cache.mode = undefined;
  16993. this._cache.minZ = undefined;
  16994. this._cache.maxZ = undefined;
  16995. this._cache.fov = undefined;
  16996. this._cache.fovMode = undefined;
  16997. this._cache.aspectRatio = undefined;
  16998. this._cache.orthoLeft = undefined;
  16999. this._cache.orthoRight = undefined;
  17000. this._cache.orthoBottom = undefined;
  17001. this._cache.orthoTop = undefined;
  17002. this._cache.renderWidth = undefined;
  17003. this._cache.renderHeight = undefined;
  17004. };
  17005. Camera.prototype._updateCache = function (ignoreParentClass) {
  17006. if (!ignoreParentClass) {
  17007. _super.prototype._updateCache.call(this);
  17008. }
  17009. this._cache.position.copyFrom(this.position);
  17010. this._cache.upVector.copyFrom(this.upVector);
  17011. };
  17012. // Synchronized
  17013. Camera.prototype._isSynchronized = function () {
  17014. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  17015. };
  17016. Camera.prototype._isSynchronizedViewMatrix = function () {
  17017. if (!_super.prototype._isSynchronized.call(this))
  17018. return false;
  17019. return this._cache.position.equals(this.position)
  17020. && this._cache.upVector.equals(this.upVector)
  17021. && this.isSynchronizedWithParent();
  17022. };
  17023. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  17024. var check = this._cache.mode === this.mode
  17025. && this._cache.minZ === this.minZ
  17026. && this._cache.maxZ === this.maxZ;
  17027. if (!check) {
  17028. return false;
  17029. }
  17030. var engine = this.getEngine();
  17031. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  17032. check = this._cache.fov === this.fov
  17033. && this._cache.fovMode === this.fovMode
  17034. && this._cache.aspectRatio === engine.getAspectRatio(this);
  17035. }
  17036. else {
  17037. check = this._cache.orthoLeft === this.orthoLeft
  17038. && this._cache.orthoRight === this.orthoRight
  17039. && this._cache.orthoBottom === this.orthoBottom
  17040. && this._cache.orthoTop === this.orthoTop
  17041. && this._cache.renderWidth === engine.getRenderWidth()
  17042. && this._cache.renderHeight === engine.getRenderHeight();
  17043. }
  17044. return check;
  17045. };
  17046. // Controls
  17047. Camera.prototype.attachControl = function (element, noPreventDefault) {
  17048. };
  17049. Camera.prototype.detachControl = function (element) {
  17050. };
  17051. Camera.prototype.update = function () {
  17052. this._checkInputs();
  17053. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  17054. this._updateRigCameras();
  17055. }
  17056. };
  17057. Camera.prototype._checkInputs = function () {
  17058. this.onAfterCheckInputsObservable.notifyObservers(this);
  17059. };
  17060. Object.defineProperty(Camera.prototype, "rigCameras", {
  17061. get: function () {
  17062. return this._rigCameras;
  17063. },
  17064. enumerable: true,
  17065. configurable: true
  17066. });
  17067. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  17068. get: function () {
  17069. return this._rigPostProcess;
  17070. },
  17071. enumerable: true,
  17072. configurable: true
  17073. });
  17074. Camera.prototype._cascadePostProcessesToRigCams = function () {
  17075. // invalidate framebuffer
  17076. if (this._postProcesses.length > 0) {
  17077. this._postProcesses[0].markTextureDirty();
  17078. }
  17079. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  17080. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  17081. var cam = this._rigCameras[i];
  17082. var rigPostProcess = cam._rigPostProcess;
  17083. // for VR rig, there does not have to be a post process
  17084. if (rigPostProcess) {
  17085. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  17086. if (isPass) {
  17087. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  17088. cam.isIntermediate = this._postProcesses.length === 0;
  17089. }
  17090. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  17091. rigPostProcess.markTextureDirty();
  17092. }
  17093. else {
  17094. cam._postProcesses = this._postProcesses.slice(0);
  17095. }
  17096. }
  17097. };
  17098. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  17099. if (insertAt === void 0) { insertAt = null; }
  17100. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  17101. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  17102. return 0;
  17103. }
  17104. if (insertAt == null || insertAt < 0) {
  17105. this._postProcesses.push(postProcess);
  17106. }
  17107. else {
  17108. this._postProcesses.splice(insertAt, 0, postProcess);
  17109. }
  17110. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  17111. return this._postProcesses.indexOf(postProcess);
  17112. };
  17113. Camera.prototype.detachPostProcess = function (postProcess) {
  17114. var idx = this._postProcesses.indexOf(postProcess);
  17115. if (idx !== -1) {
  17116. this._postProcesses.splice(idx, 1);
  17117. }
  17118. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  17119. };
  17120. Camera.prototype.getWorldMatrix = function () {
  17121. if (!this._worldMatrix) {
  17122. this._worldMatrix = BABYLON.Matrix.Identity();
  17123. }
  17124. var viewMatrix = this.getViewMatrix();
  17125. viewMatrix.invertToRef(this._worldMatrix);
  17126. return this._worldMatrix;
  17127. };
  17128. Camera.prototype._getViewMatrix = function () {
  17129. return BABYLON.Matrix.Identity();
  17130. };
  17131. Camera.prototype.getViewMatrix = function (force) {
  17132. if (!force && this._isSynchronizedViewMatrix()) {
  17133. return this._computedViewMatrix;
  17134. }
  17135. this.updateCache();
  17136. this._computedViewMatrix = this._getViewMatrix();
  17137. this._currentRenderId = this.getScene().getRenderId();
  17138. this._refreshFrustumPlanes = true;
  17139. if (!this.parent || !this.parent.getWorldMatrix) {
  17140. this._globalPosition.copyFrom(this.position);
  17141. }
  17142. else {
  17143. if (!this._worldMatrix) {
  17144. this._worldMatrix = BABYLON.Matrix.Identity();
  17145. }
  17146. this._computedViewMatrix.invertToRef(this._worldMatrix);
  17147. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  17148. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  17149. this._computedViewMatrix.invert();
  17150. this._markSyncedWithParent();
  17151. }
  17152. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  17153. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  17154. }
  17155. this.onViewMatrixChangedObservable.notifyObservers(this);
  17156. return this._computedViewMatrix;
  17157. };
  17158. Camera.prototype.freezeProjectionMatrix = function (projection) {
  17159. this._doNotComputeProjectionMatrix = true;
  17160. if (projection !== undefined) {
  17161. this._projectionMatrix = projection;
  17162. }
  17163. };
  17164. ;
  17165. Camera.prototype.unfreezeProjectionMatrix = function () {
  17166. this._doNotComputeProjectionMatrix = false;
  17167. };
  17168. ;
  17169. Camera.prototype.getProjectionMatrix = function (force) {
  17170. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  17171. return this._projectionMatrix;
  17172. }
  17173. // Cache
  17174. this._cache.mode = this.mode;
  17175. this._cache.minZ = this.minZ;
  17176. this._cache.maxZ = this.maxZ;
  17177. // Matrix
  17178. this._refreshFrustumPlanes = true;
  17179. var engine = this.getEngine();
  17180. var scene = this.getScene();
  17181. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  17182. this._cache.fov = this.fov;
  17183. this._cache.fovMode = this.fovMode;
  17184. this._cache.aspectRatio = engine.getAspectRatio(this);
  17185. if (this.minZ <= 0) {
  17186. this.minZ = 0.1;
  17187. }
  17188. if (scene.useRightHandedSystem) {
  17189. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  17190. }
  17191. else {
  17192. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  17193. }
  17194. }
  17195. else {
  17196. var halfWidth = engine.getRenderWidth() / 2.0;
  17197. var halfHeight = engine.getRenderHeight() / 2.0;
  17198. if (scene.useRightHandedSystem) {
  17199. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  17200. }
  17201. else {
  17202. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  17203. }
  17204. this._cache.orthoLeft = this.orthoLeft;
  17205. this._cache.orthoRight = this.orthoRight;
  17206. this._cache.orthoBottom = this.orthoBottom;
  17207. this._cache.orthoTop = this.orthoTop;
  17208. this._cache.renderWidth = engine.getRenderWidth();
  17209. this._cache.renderHeight = engine.getRenderHeight();
  17210. }
  17211. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  17212. return this._projectionMatrix;
  17213. };
  17214. Camera.prototype.getTranformationMatrix = function () {
  17215. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  17216. return this._transformMatrix;
  17217. };
  17218. Camera.prototype.updateFrustumPlanes = function () {
  17219. if (!this._refreshFrustumPlanes) {
  17220. return;
  17221. }
  17222. this.getTranformationMatrix();
  17223. if (!this._frustumPlanes) {
  17224. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  17225. }
  17226. else {
  17227. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  17228. }
  17229. this._refreshFrustumPlanes = false;
  17230. };
  17231. Camera.prototype.isInFrustum = function (target) {
  17232. this.updateFrustumPlanes();
  17233. return target.isInFrustum(this._frustumPlanes);
  17234. };
  17235. Camera.prototype.isCompletelyInFrustum = function (target) {
  17236. this.updateFrustumPlanes();
  17237. return target.isCompletelyInFrustum(this._frustumPlanes);
  17238. };
  17239. Camera.prototype.getForwardRay = function (length, transform, origin) {
  17240. if (length === void 0) { length = 100; }
  17241. if (!transform) {
  17242. transform = this.getWorldMatrix();
  17243. }
  17244. if (!origin) {
  17245. origin = this.position;
  17246. }
  17247. var forward = new BABYLON.Vector3(0, 0, 1);
  17248. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  17249. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  17250. return new BABYLON.Ray(origin, direction, length);
  17251. };
  17252. Camera.prototype.dispose = function () {
  17253. // Observables
  17254. this.onViewMatrixChangedObservable.clear();
  17255. this.onProjectionMatrixChangedObservable.clear();
  17256. this.onAfterCheckInputsObservable.clear();
  17257. this.onRestoreStateObservable.clear();
  17258. // Inputs
  17259. if (this.inputs) {
  17260. this.inputs.clear();
  17261. }
  17262. // Animations
  17263. this.getScene().stopAnimation(this);
  17264. // Remove from scene
  17265. this.getScene().removeCamera(this);
  17266. while (this._rigCameras.length > 0) {
  17267. var camera = this._rigCameras.pop();
  17268. if (camera) {
  17269. camera.dispose();
  17270. }
  17271. }
  17272. // Postprocesses
  17273. if (this._rigPostProcess) {
  17274. this._rigPostProcess.dispose(this);
  17275. this._rigPostProcess = null;
  17276. this._postProcesses = [];
  17277. }
  17278. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  17279. this._rigPostProcess = null;
  17280. this._postProcesses = [];
  17281. }
  17282. else {
  17283. var i = this._postProcesses.length;
  17284. while (--i >= 0) {
  17285. this._postProcesses[i].dispose(this);
  17286. }
  17287. }
  17288. // Render targets
  17289. var i = this.customRenderTargets.length;
  17290. while (--i >= 0) {
  17291. this.customRenderTargets[i].dispose();
  17292. }
  17293. this.customRenderTargets = [];
  17294. // Active Meshes
  17295. this._activeMeshes.dispose();
  17296. _super.prototype.dispose.call(this);
  17297. };
  17298. Object.defineProperty(Camera.prototype, "leftCamera", {
  17299. // ---- Camera rigs section ----
  17300. get: function () {
  17301. if (this._rigCameras.length < 1) {
  17302. return null;
  17303. }
  17304. return this._rigCameras[0];
  17305. },
  17306. enumerable: true,
  17307. configurable: true
  17308. });
  17309. Object.defineProperty(Camera.prototype, "rightCamera", {
  17310. get: function () {
  17311. if (this._rigCameras.length < 2) {
  17312. return null;
  17313. }
  17314. return this._rigCameras[1];
  17315. },
  17316. enumerable: true,
  17317. configurable: true
  17318. });
  17319. Camera.prototype.getLeftTarget = function () {
  17320. if (this._rigCameras.length < 1) {
  17321. return null;
  17322. }
  17323. return this._rigCameras[0].getTarget();
  17324. };
  17325. Camera.prototype.getRightTarget = function () {
  17326. if (this._rigCameras.length < 2) {
  17327. return null;
  17328. }
  17329. return this._rigCameras[1].getTarget();
  17330. };
  17331. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  17332. if (this.cameraRigMode === mode) {
  17333. return;
  17334. }
  17335. while (this._rigCameras.length > 0) {
  17336. var camera = this._rigCameras.pop();
  17337. if (camera) {
  17338. camera.dispose();
  17339. }
  17340. }
  17341. this.cameraRigMode = mode;
  17342. this._cameraRigParams = {};
  17343. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  17344. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  17345. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  17346. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  17347. // create the rig cameras, unless none
  17348. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  17349. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  17350. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  17351. if (leftCamera && rightCamera) {
  17352. this._rigCameras.push(leftCamera);
  17353. this._rigCameras.push(rightCamera);
  17354. }
  17355. }
  17356. switch (this.cameraRigMode) {
  17357. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  17358. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  17359. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  17360. break;
  17361. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  17362. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  17363. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  17364. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  17365. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  17366. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  17367. break;
  17368. case Camera.RIG_MODE_VR:
  17369. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  17370. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  17371. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  17372. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  17373. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  17374. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  17375. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  17376. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  17377. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  17378. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  17379. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  17380. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  17381. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  17382. if (metrics.compensateDistortion) {
  17383. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  17384. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  17385. }
  17386. break;
  17387. case Camera.RIG_MODE_WEBVR:
  17388. if (rigParams.vrDisplay) {
  17389. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  17390. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  17391. //Left eye
  17392. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  17393. this._rigCameras[0].setCameraRigParameter("left", true);
  17394. //leaving this for future reference
  17395. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  17396. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  17397. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  17398. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  17399. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  17400. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  17401. this._rigCameras[0].parent = this;
  17402. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  17403. //Right eye
  17404. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  17405. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  17406. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  17407. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  17408. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  17409. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  17410. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  17411. this._rigCameras[1].parent = this;
  17412. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  17413. if (Camera.UseAlternateWebVRRendering) {
  17414. this._rigCameras[1]._skipRendering = true;
  17415. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  17416. }
  17417. }
  17418. break;
  17419. }
  17420. this._cascadePostProcessesToRigCams();
  17421. this.update();
  17422. };
  17423. Camera.prototype._getVRProjectionMatrix = function () {
  17424. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  17425. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  17426. return this._projectionMatrix;
  17427. };
  17428. Camera.prototype._updateCameraRotationMatrix = function () {
  17429. //Here for WebVR
  17430. };
  17431. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  17432. //Here for WebVR
  17433. };
  17434. /**
  17435. * This function MUST be overwritten by the different WebVR cameras available.
  17436. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  17437. */
  17438. Camera.prototype._getWebVRProjectionMatrix = function () {
  17439. return BABYLON.Matrix.Identity();
  17440. };
  17441. /**
  17442. * This function MUST be overwritten by the different WebVR cameras available.
  17443. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  17444. */
  17445. Camera.prototype._getWebVRViewMatrix = function () {
  17446. return BABYLON.Matrix.Identity();
  17447. };
  17448. Camera.prototype.setCameraRigParameter = function (name, value) {
  17449. if (!this._cameraRigParams) {
  17450. this._cameraRigParams = {};
  17451. }
  17452. this._cameraRigParams[name] = value;
  17453. //provisionnally:
  17454. if (name === "interaxialDistance") {
  17455. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  17456. }
  17457. };
  17458. /**
  17459. * needs to be overridden by children so sub has required properties to be copied
  17460. */
  17461. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  17462. return null;
  17463. };
  17464. /**
  17465. * May need to be overridden by children
  17466. */
  17467. Camera.prototype._updateRigCameras = function () {
  17468. for (var i = 0; i < this._rigCameras.length; i++) {
  17469. this._rigCameras[i].minZ = this.minZ;
  17470. this._rigCameras[i].maxZ = this.maxZ;
  17471. this._rigCameras[i].fov = this.fov;
  17472. }
  17473. // only update viewport when ANAGLYPH
  17474. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  17475. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  17476. }
  17477. };
  17478. Camera.prototype._setupInputs = function () {
  17479. };
  17480. Camera.prototype.serialize = function () {
  17481. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  17482. // Type
  17483. serializationObject.type = this.getClassName();
  17484. // Parent
  17485. if (this.parent) {
  17486. serializationObject.parentId = this.parent.id;
  17487. }
  17488. if (this.inputs) {
  17489. this.inputs.serialize(serializationObject);
  17490. }
  17491. // Animations
  17492. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17493. serializationObject.ranges = this.serializeAnimationRanges();
  17494. return serializationObject;
  17495. };
  17496. Camera.prototype.clone = function (name) {
  17497. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  17498. };
  17499. Camera.prototype.getDirection = function (localAxis) {
  17500. var result = BABYLON.Vector3.Zero();
  17501. this.getDirectionToRef(localAxis, result);
  17502. return result;
  17503. };
  17504. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  17505. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  17506. };
  17507. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  17508. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  17509. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  17510. switch (type) {
  17511. case "ArcRotateCamera":
  17512. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  17513. case "DeviceOrientationCamera":
  17514. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  17515. case "FollowCamera":
  17516. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  17517. case "ArcFollowCamera":
  17518. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  17519. case "GamepadCamera":
  17520. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  17521. case "TouchCamera":
  17522. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  17523. case "VirtualJoysticksCamera":
  17524. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  17525. case "WebVRFreeCamera":
  17526. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  17527. case "WebVRGamepadCamera":
  17528. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  17529. case "VRDeviceOrientationFreeCamera":
  17530. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  17531. case "VRDeviceOrientationGamepadCamera":
  17532. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  17533. case "AnaglyphArcRotateCamera":
  17534. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  17535. case "AnaglyphFreeCamera":
  17536. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  17537. case "AnaglyphGamepadCamera":
  17538. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  17539. case "AnaglyphUniversalCamera":
  17540. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  17541. case "StereoscopicArcRotateCamera":
  17542. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  17543. case "StereoscopicFreeCamera":
  17544. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  17545. case "StereoscopicGamepadCamera":
  17546. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  17547. case "StereoscopicUniversalCamera":
  17548. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  17549. case "FreeCamera":// Forcing Universal here
  17550. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  17551. default:// Universal Camera is the default value
  17552. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  17553. }
  17554. };
  17555. Camera.prototype.computeWorldMatrix = function () {
  17556. return this.getWorldMatrix();
  17557. };
  17558. Camera.Parse = function (parsedCamera, scene) {
  17559. var type = parsedCamera.type;
  17560. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  17561. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  17562. // Parent
  17563. if (parsedCamera.parentId) {
  17564. camera._waitingParentId = parsedCamera.parentId;
  17565. }
  17566. //If camera has an input manager, let it parse inputs settings
  17567. if (camera.inputs) {
  17568. camera.inputs.parse(parsedCamera);
  17569. camera._setupInputs();
  17570. }
  17571. if (camera.setPosition) {
  17572. camera.position.copyFromFloats(0, 0, 0);
  17573. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  17574. }
  17575. // Target
  17576. if (parsedCamera.target) {
  17577. if (camera.setTarget) {
  17578. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  17579. }
  17580. }
  17581. // Apply 3d rig, when found
  17582. if (parsedCamera.cameraRigMode) {
  17583. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  17584. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  17585. }
  17586. // Animations
  17587. if (parsedCamera.animations) {
  17588. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  17589. var parsedAnimation = parsedCamera.animations[animationIndex];
  17590. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17591. }
  17592. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  17593. }
  17594. if (parsedCamera.autoAnimate) {
  17595. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  17596. }
  17597. return camera;
  17598. };
  17599. // Statics
  17600. Camera._PERSPECTIVE_CAMERA = 0;
  17601. Camera._ORTHOGRAPHIC_CAMERA = 1;
  17602. Camera._FOVMODE_VERTICAL_FIXED = 0;
  17603. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  17604. Camera._RIG_MODE_NONE = 0;
  17605. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  17606. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  17607. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  17608. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  17609. Camera._RIG_MODE_VR = 20;
  17610. Camera._RIG_MODE_WEBVR = 21;
  17611. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  17612. Camera.UseAlternateWebVRRendering = false;
  17613. __decorate([
  17614. BABYLON.serializeAsVector3()
  17615. ], Camera.prototype, "position", void 0);
  17616. __decorate([
  17617. BABYLON.serializeAsVector3()
  17618. ], Camera.prototype, "upVector", void 0);
  17619. __decorate([
  17620. BABYLON.serialize()
  17621. ], Camera.prototype, "orthoLeft", void 0);
  17622. __decorate([
  17623. BABYLON.serialize()
  17624. ], Camera.prototype, "orthoRight", void 0);
  17625. __decorate([
  17626. BABYLON.serialize()
  17627. ], Camera.prototype, "orthoBottom", void 0);
  17628. __decorate([
  17629. BABYLON.serialize()
  17630. ], Camera.prototype, "orthoTop", void 0);
  17631. __decorate([
  17632. BABYLON.serialize()
  17633. ], Camera.prototype, "fov", void 0);
  17634. __decorate([
  17635. BABYLON.serialize()
  17636. ], Camera.prototype, "minZ", void 0);
  17637. __decorate([
  17638. BABYLON.serialize()
  17639. ], Camera.prototype, "maxZ", void 0);
  17640. __decorate([
  17641. BABYLON.serialize()
  17642. ], Camera.prototype, "inertia", void 0);
  17643. __decorate([
  17644. BABYLON.serialize()
  17645. ], Camera.prototype, "mode", void 0);
  17646. __decorate([
  17647. BABYLON.serialize()
  17648. ], Camera.prototype, "layerMask", void 0);
  17649. __decorate([
  17650. BABYLON.serialize()
  17651. ], Camera.prototype, "fovMode", void 0);
  17652. __decorate([
  17653. BABYLON.serialize()
  17654. ], Camera.prototype, "cameraRigMode", void 0);
  17655. __decorate([
  17656. BABYLON.serialize()
  17657. ], Camera.prototype, "interaxialDistance", void 0);
  17658. __decorate([
  17659. BABYLON.serialize()
  17660. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  17661. return Camera;
  17662. }(BABYLON.Node));
  17663. BABYLON.Camera = Camera;
  17664. })(BABYLON || (BABYLON = {}));
  17665. //# sourceMappingURL=babylon.camera.js.map
  17666. var BABYLON;
  17667. (function (BABYLON) {
  17668. var RenderingManager = /** @class */ (function () {
  17669. function RenderingManager(scene) {
  17670. this._renderingGroups = new Array();
  17671. this._autoClearDepthStencil = {};
  17672. this._customOpaqueSortCompareFn = {};
  17673. this._customAlphaTestSortCompareFn = {};
  17674. this._customTransparentSortCompareFn = {};
  17675. this._renderinGroupInfo = null;
  17676. this._scene = scene;
  17677. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  17678. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  17679. }
  17680. }
  17681. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  17682. if (depth === void 0) { depth = true; }
  17683. if (stencil === void 0) { stencil = true; }
  17684. if (this._depthStencilBufferAlreadyCleaned) {
  17685. return;
  17686. }
  17687. this._scene.getEngine().clear(null, false, depth, stencil);
  17688. this._depthStencilBufferAlreadyCleaned = true;
  17689. };
  17690. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  17691. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  17692. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  17693. var info = null;
  17694. if (observable) {
  17695. if (!this._renderinGroupInfo) {
  17696. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  17697. }
  17698. info = this._renderinGroupInfo;
  17699. info.scene = this._scene;
  17700. info.camera = this._scene.activeCamera;
  17701. }
  17702. // Dispatch sprites
  17703. if (renderSprites) {
  17704. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  17705. var manager = this._scene.spriteManagers[index];
  17706. this.dispatchSprites(manager);
  17707. }
  17708. }
  17709. // Render
  17710. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  17711. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  17712. var renderingGroup = this._renderingGroups[index];
  17713. if (!renderingGroup && !observable)
  17714. continue;
  17715. var renderingGroupMask = 0;
  17716. // Fire PRECLEAR stage
  17717. if (observable && info) {
  17718. renderingGroupMask = Math.pow(2, index);
  17719. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  17720. info.renderingGroupId = index;
  17721. observable.notifyObservers(info, renderingGroupMask);
  17722. }
  17723. // Clear depth/stencil if needed
  17724. if (RenderingManager.AUTOCLEAR) {
  17725. var autoClear = this._autoClearDepthStencil[index];
  17726. if (autoClear && autoClear.autoClear) {
  17727. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  17728. }
  17729. }
  17730. if (observable && info) {
  17731. // Fire PREOPAQUE stage
  17732. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  17733. observable.notifyObservers(info, renderingGroupMask);
  17734. // Fire PRETRANSPARENT stage
  17735. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  17736. observable.notifyObservers(info, renderingGroupMask);
  17737. }
  17738. if (renderingGroup)
  17739. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  17740. // Fire POSTTRANSPARENT stage
  17741. if (observable && info) {
  17742. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  17743. observable.notifyObservers(info, renderingGroupMask);
  17744. }
  17745. }
  17746. };
  17747. RenderingManager.prototype.reset = function () {
  17748. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  17749. var renderingGroup = this._renderingGroups[index];
  17750. if (renderingGroup) {
  17751. renderingGroup.prepare();
  17752. }
  17753. }
  17754. };
  17755. RenderingManager.prototype.dispose = function () {
  17756. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  17757. var renderingGroup = this._renderingGroups[index];
  17758. if (renderingGroup) {
  17759. renderingGroup.dispose();
  17760. }
  17761. }
  17762. this._renderingGroups.length = 0;
  17763. };
  17764. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  17765. if (this._renderingGroups[renderingGroupId] === undefined) {
  17766. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  17767. }
  17768. };
  17769. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  17770. var renderingGroupId = spriteManager.renderingGroupId || 0;
  17771. this._prepareRenderingGroup(renderingGroupId);
  17772. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  17773. };
  17774. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  17775. var renderingGroupId = particleSystem.renderingGroupId || 0;
  17776. this._prepareRenderingGroup(renderingGroupId);
  17777. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  17778. };
  17779. /**
  17780. * @param subMesh The submesh to dispatch
  17781. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  17782. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  17783. */
  17784. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  17785. if (mesh === undefined) {
  17786. mesh = subMesh.getMesh();
  17787. }
  17788. var renderingGroupId = mesh.renderingGroupId || 0;
  17789. this._prepareRenderingGroup(renderingGroupId);
  17790. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  17791. };
  17792. /**
  17793. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  17794. * This allowed control for front to back rendering or reversly depending of the special needs.
  17795. *
  17796. * @param renderingGroupId The rendering group id corresponding to its index
  17797. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  17798. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  17799. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  17800. */
  17801. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  17802. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  17803. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  17804. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  17805. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  17806. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  17807. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  17808. if (this._renderingGroups[renderingGroupId]) {
  17809. var group = this._renderingGroups[renderingGroupId];
  17810. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  17811. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  17812. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  17813. }
  17814. };
  17815. /**
  17816. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  17817. *
  17818. * @param renderingGroupId The rendering group id corresponding to its index
  17819. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  17820. * @param depth Automatically clears depth between groups if true and autoClear is true.
  17821. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  17822. */
  17823. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  17824. if (depth === void 0) { depth = true; }
  17825. if (stencil === void 0) { stencil = true; }
  17826. this._autoClearDepthStencil[renderingGroupId] = {
  17827. autoClear: autoClearDepthStencil,
  17828. depth: depth,
  17829. stencil: stencil
  17830. };
  17831. };
  17832. /**
  17833. * The max id used for rendering groups (not included)
  17834. */
  17835. RenderingManager.MAX_RENDERINGGROUPS = 4;
  17836. /**
  17837. * The min id used for rendering groups (included)
  17838. */
  17839. RenderingManager.MIN_RENDERINGGROUPS = 0;
  17840. /**
  17841. * Used to globally prevent autoclearing scenes.
  17842. */
  17843. RenderingManager.AUTOCLEAR = true;
  17844. return RenderingManager;
  17845. }());
  17846. BABYLON.RenderingManager = RenderingManager;
  17847. })(BABYLON || (BABYLON = {}));
  17848. //# sourceMappingURL=babylon.renderingManager.js.map
  17849. var BABYLON;
  17850. (function (BABYLON) {
  17851. var RenderingGroup = /** @class */ (function () {
  17852. /**
  17853. * Creates a new rendering group.
  17854. * @param index The rendering group index
  17855. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  17856. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  17857. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  17858. */
  17859. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  17860. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  17861. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  17862. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  17863. this.index = index;
  17864. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  17865. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  17866. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  17867. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  17868. this._particleSystems = new BABYLON.SmartArray(256);
  17869. this._spriteManagers = new BABYLON.SmartArray(256);
  17870. this._edgesRenderers = new BABYLON.SmartArray(16);
  17871. this._scene = scene;
  17872. this.opaqueSortCompareFn = opaqueSortCompareFn;
  17873. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  17874. this.transparentSortCompareFn = transparentSortCompareFn;
  17875. }
  17876. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  17877. /**
  17878. * Set the opaque sort comparison function.
  17879. * If null the sub meshes will be render in the order they were created
  17880. */
  17881. set: function (value) {
  17882. this._opaqueSortCompareFn = value;
  17883. if (value) {
  17884. this._renderOpaque = this.renderOpaqueSorted;
  17885. }
  17886. else {
  17887. this._renderOpaque = RenderingGroup.renderUnsorted;
  17888. }
  17889. },
  17890. enumerable: true,
  17891. configurable: true
  17892. });
  17893. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  17894. /**
  17895. * Set the alpha test sort comparison function.
  17896. * If null the sub meshes will be render in the order they were created
  17897. */
  17898. set: function (value) {
  17899. this._alphaTestSortCompareFn = value;
  17900. if (value) {
  17901. this._renderAlphaTest = this.renderAlphaTestSorted;
  17902. }
  17903. else {
  17904. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  17905. }
  17906. },
  17907. enumerable: true,
  17908. configurable: true
  17909. });
  17910. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  17911. /**
  17912. * Set the transparent sort comparison function.
  17913. * If null the sub meshes will be render in the order they were created
  17914. */
  17915. set: function (value) {
  17916. if (value) {
  17917. this._transparentSortCompareFn = value;
  17918. }
  17919. else {
  17920. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  17921. }
  17922. this._renderTransparent = this.renderTransparentSorted;
  17923. },
  17924. enumerable: true,
  17925. configurable: true
  17926. });
  17927. /**
  17928. * Render all the sub meshes contained in the group.
  17929. * @param customRenderFunction Used to override the default render behaviour of the group.
  17930. * @returns true if rendered some submeshes.
  17931. */
  17932. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  17933. if (customRenderFunction) {
  17934. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  17935. return;
  17936. }
  17937. var engine = this._scene.getEngine();
  17938. // Depth only
  17939. if (this._depthOnlySubMeshes.length !== 0) {
  17940. engine.setAlphaTesting(true);
  17941. engine.setColorWrite(false);
  17942. this._renderAlphaTest(this._depthOnlySubMeshes);
  17943. engine.setAlphaTesting(false);
  17944. engine.setColorWrite(true);
  17945. }
  17946. // Opaque
  17947. if (this._opaqueSubMeshes.length !== 0) {
  17948. this._renderOpaque(this._opaqueSubMeshes);
  17949. }
  17950. // Alpha test
  17951. if (this._alphaTestSubMeshes.length !== 0) {
  17952. engine.setAlphaTesting(true);
  17953. this._renderAlphaTest(this._alphaTestSubMeshes);
  17954. engine.setAlphaTesting(false);
  17955. }
  17956. var stencilState = engine.getStencilBuffer();
  17957. engine.setStencilBuffer(false);
  17958. // Sprites
  17959. if (renderSprites) {
  17960. this._renderSprites();
  17961. }
  17962. // Particles
  17963. if (renderParticles) {
  17964. this._renderParticles(activeMeshes);
  17965. }
  17966. if (this.onBeforeTransparentRendering) {
  17967. this.onBeforeTransparentRendering();
  17968. }
  17969. // Transparent
  17970. if (this._transparentSubMeshes.length !== 0) {
  17971. this._renderTransparent(this._transparentSubMeshes);
  17972. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17973. }
  17974. // Set back stencil to false in case it changes before the edge renderer.
  17975. engine.setStencilBuffer(false);
  17976. // Edges
  17977. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  17978. this._edgesRenderers.data[edgesRendererIndex].render();
  17979. }
  17980. // Restore Stencil state.
  17981. engine.setStencilBuffer(stencilState);
  17982. };
  17983. /**
  17984. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  17985. * @param subMeshes The submeshes to render
  17986. */
  17987. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  17988. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  17989. };
  17990. /**
  17991. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  17992. * @param subMeshes The submeshes to render
  17993. */
  17994. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  17995. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  17996. };
  17997. /**
  17998. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  17999. * @param subMeshes The submeshes to render
  18000. */
  18001. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  18002. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  18003. };
  18004. /**
  18005. * Renders the submeshes in a specified order.
  18006. * @param subMeshes The submeshes to sort before render
  18007. * @param sortCompareFn The comparison function use to sort
  18008. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  18009. * @param transparent Specifies to activate blending if true
  18010. */
  18011. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  18012. var subIndex = 0;
  18013. var subMesh;
  18014. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  18015. for (; subIndex < subMeshes.length; subIndex++) {
  18016. subMesh = subMeshes.data[subIndex];
  18017. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  18018. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  18019. }
  18020. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  18021. if (sortCompareFn) {
  18022. sortedArray.sort(sortCompareFn);
  18023. }
  18024. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  18025. subMesh = sortedArray[subIndex];
  18026. if (transparent) {
  18027. var material = subMesh.getMaterial();
  18028. if (material && material.needDepthPrePass) {
  18029. var engine = material.getScene().getEngine();
  18030. engine.setColorWrite(false);
  18031. engine.setAlphaTesting(true);
  18032. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  18033. subMesh.render(false);
  18034. engine.setAlphaTesting(false);
  18035. engine.setColorWrite(true);
  18036. }
  18037. }
  18038. subMesh.render(transparent);
  18039. }
  18040. };
  18041. /**
  18042. * Renders the submeshes in the order they were dispatched (no sort applied).
  18043. * @param subMeshes The submeshes to render
  18044. */
  18045. RenderingGroup.renderUnsorted = function (subMeshes) {
  18046. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  18047. var submesh = subMeshes.data[subIndex];
  18048. submesh.render(false);
  18049. }
  18050. };
  18051. /**
  18052. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18053. * are rendered back to front if in the same alpha index.
  18054. *
  18055. * @param a The first submesh
  18056. * @param b The second submesh
  18057. * @returns The result of the comparison
  18058. */
  18059. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  18060. // Alpha index first
  18061. if (a._alphaIndex > b._alphaIndex) {
  18062. return 1;
  18063. }
  18064. if (a._alphaIndex < b._alphaIndex) {
  18065. return -1;
  18066. }
  18067. // Then distance to camera
  18068. return RenderingGroup.backToFrontSortCompare(a, b);
  18069. };
  18070. /**
  18071. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18072. * are rendered back to front.
  18073. *
  18074. * @param a The first submesh
  18075. * @param b The second submesh
  18076. * @returns The result of the comparison
  18077. */
  18078. RenderingGroup.backToFrontSortCompare = function (a, b) {
  18079. // Then distance to camera
  18080. if (a._distanceToCamera < b._distanceToCamera) {
  18081. return 1;
  18082. }
  18083. if (a._distanceToCamera > b._distanceToCamera) {
  18084. return -1;
  18085. }
  18086. return 0;
  18087. };
  18088. /**
  18089. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18090. * are rendered front to back (prevent overdraw).
  18091. *
  18092. * @param a The first submesh
  18093. * @param b The second submesh
  18094. * @returns The result of the comparison
  18095. */
  18096. RenderingGroup.frontToBackSortCompare = function (a, b) {
  18097. // Then distance to camera
  18098. if (a._distanceToCamera < b._distanceToCamera) {
  18099. return -1;
  18100. }
  18101. if (a._distanceToCamera > b._distanceToCamera) {
  18102. return 1;
  18103. }
  18104. return 0;
  18105. };
  18106. /**
  18107. * Resets the different lists of submeshes to prepare a new frame.
  18108. */
  18109. RenderingGroup.prototype.prepare = function () {
  18110. this._opaqueSubMeshes.reset();
  18111. this._transparentSubMeshes.reset();
  18112. this._alphaTestSubMeshes.reset();
  18113. this._depthOnlySubMeshes.reset();
  18114. this._particleSystems.reset();
  18115. this._spriteManagers.reset();
  18116. this._edgesRenderers.reset();
  18117. };
  18118. RenderingGroup.prototype.dispose = function () {
  18119. this._opaqueSubMeshes.dispose();
  18120. this._transparentSubMeshes.dispose();
  18121. this._alphaTestSubMeshes.dispose();
  18122. this._depthOnlySubMeshes.dispose();
  18123. this._particleSystems.dispose();
  18124. this._spriteManagers.dispose();
  18125. this._edgesRenderers.dispose();
  18126. };
  18127. /**
  18128. * Inserts the submesh in its correct queue depending on its material.
  18129. * @param subMesh The submesh to dispatch
  18130. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  18131. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  18132. */
  18133. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  18134. // Get mesh and materials if not provided
  18135. if (mesh === undefined) {
  18136. mesh = subMesh.getMesh();
  18137. }
  18138. if (material === undefined) {
  18139. material = subMesh.getMaterial();
  18140. }
  18141. if (material === null || material === undefined) {
  18142. return;
  18143. }
  18144. if (material.needAlphaBlendingForMesh(mesh)) {
  18145. this._transparentSubMeshes.push(subMesh);
  18146. }
  18147. else if (material.needAlphaTesting()) {
  18148. if (material.needDepthPrePass) {
  18149. this._depthOnlySubMeshes.push(subMesh);
  18150. }
  18151. this._alphaTestSubMeshes.push(subMesh);
  18152. }
  18153. else {
  18154. if (material.needDepthPrePass) {
  18155. this._depthOnlySubMeshes.push(subMesh);
  18156. }
  18157. this._opaqueSubMeshes.push(subMesh); // Opaque
  18158. }
  18159. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  18160. this._edgesRenderers.push(mesh._edgesRenderer);
  18161. }
  18162. };
  18163. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  18164. this._spriteManagers.push(spriteManager);
  18165. };
  18166. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  18167. this._particleSystems.push(particleSystem);
  18168. };
  18169. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  18170. if (this._particleSystems.length === 0) {
  18171. return;
  18172. }
  18173. // Particles
  18174. var activeCamera = this._scene.activeCamera;
  18175. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  18176. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  18177. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  18178. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  18179. continue;
  18180. }
  18181. var emitter = particleSystem.emitter;
  18182. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  18183. this._scene._activeParticles.addCount(particleSystem.render(), false);
  18184. }
  18185. }
  18186. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  18187. };
  18188. RenderingGroup.prototype._renderSprites = function () {
  18189. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  18190. return;
  18191. }
  18192. // Sprites
  18193. var activeCamera = this._scene.activeCamera;
  18194. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  18195. for (var id = 0; id < this._spriteManagers.length; id++) {
  18196. var spriteManager = this._spriteManagers.data[id];
  18197. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  18198. spriteManager.render();
  18199. }
  18200. }
  18201. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  18202. };
  18203. return RenderingGroup;
  18204. }());
  18205. BABYLON.RenderingGroup = RenderingGroup;
  18206. })(BABYLON || (BABYLON = {}));
  18207. //# sourceMappingURL=babylon.renderingGroup.js.map
  18208. var BABYLON;
  18209. (function (BABYLON) {
  18210. var ClickInfo = /** @class */ (function () {
  18211. function ClickInfo() {
  18212. this._singleClick = false;
  18213. this._doubleClick = false;
  18214. this._hasSwiped = false;
  18215. this._ignore = false;
  18216. }
  18217. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  18218. get: function () {
  18219. return this._singleClick;
  18220. },
  18221. set: function (b) {
  18222. this._singleClick = b;
  18223. },
  18224. enumerable: true,
  18225. configurable: true
  18226. });
  18227. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  18228. get: function () {
  18229. return this._doubleClick;
  18230. },
  18231. set: function (b) {
  18232. this._doubleClick = b;
  18233. },
  18234. enumerable: true,
  18235. configurable: true
  18236. });
  18237. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  18238. get: function () {
  18239. return this._hasSwiped;
  18240. },
  18241. set: function (b) {
  18242. this._hasSwiped = b;
  18243. },
  18244. enumerable: true,
  18245. configurable: true
  18246. });
  18247. Object.defineProperty(ClickInfo.prototype, "ignore", {
  18248. get: function () {
  18249. return this._ignore;
  18250. },
  18251. set: function (b) {
  18252. this._ignore = b;
  18253. },
  18254. enumerable: true,
  18255. configurable: true
  18256. });
  18257. return ClickInfo;
  18258. }());
  18259. /**
  18260. * This class is used by the onRenderingGroupObservable
  18261. */
  18262. var RenderingGroupInfo = /** @class */ (function () {
  18263. function RenderingGroupInfo() {
  18264. }
  18265. /**
  18266. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  18267. * This stage will be fired no matter what
  18268. */
  18269. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  18270. /**
  18271. * Called before opaque object are rendered.
  18272. * This stage will be fired only if there's 3D Opaque content to render
  18273. */
  18274. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  18275. /**
  18276. * Called after the opaque objects are rendered and before the transparent ones
  18277. * This stage will be fired only if there's 3D transparent content to render
  18278. */
  18279. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  18280. /**
  18281. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  18282. * This stage will be fired no matter what
  18283. */
  18284. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  18285. return RenderingGroupInfo;
  18286. }());
  18287. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  18288. /**
  18289. * Represents a scene to be rendered by the engine.
  18290. * @see http://doc.babylonjs.com/page.php?p=21911
  18291. */
  18292. var Scene = /** @class */ (function () {
  18293. /**
  18294. * @constructor
  18295. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  18296. */
  18297. function Scene(engine) {
  18298. // Members
  18299. this.autoClear = true;
  18300. this.autoClearDepthAndStencil = true;
  18301. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  18302. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  18303. this.forceWireframe = false;
  18304. this._forcePointsCloud = false;
  18305. this.forceShowBoundingBoxes = false;
  18306. this.animationsEnabled = true;
  18307. this.useConstantAnimationDeltaTime = false;
  18308. this.constantlyUpdateMeshUnderPointer = false;
  18309. this.hoverCursor = "pointer";
  18310. this.defaultCursor = "";
  18311. /**
  18312. * This is used to call preventDefault() on pointer down
  18313. * in order to block unwanted artifacts like system double clicks
  18314. */
  18315. this.preventDefaultOnPointerDown = true;
  18316. // Metadata
  18317. this.metadata = null;
  18318. /**
  18319. * An event triggered when the scene is disposed.
  18320. * @type {BABYLON.Observable}
  18321. */
  18322. this.onDisposeObservable = new BABYLON.Observable();
  18323. /**
  18324. * An event triggered before rendering the scene (right after animations and physics)
  18325. * @type {BABYLON.Observable}
  18326. */
  18327. this.onBeforeRenderObservable = new BABYLON.Observable();
  18328. /**
  18329. * An event triggered after rendering the scene
  18330. * @type {BABYLON.Observable}
  18331. */
  18332. this.onAfterRenderObservable = new BABYLON.Observable();
  18333. /**
  18334. * An event triggered before animating the scene
  18335. * @type {BABYLON.Observable}
  18336. */
  18337. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  18338. /**
  18339. * An event triggered after animations processing
  18340. * @type {BABYLON.Observable}
  18341. */
  18342. this.onAfterAnimationsObservable = new BABYLON.Observable();
  18343. /**
  18344. * An event triggered before draw calls are ready to be sent
  18345. * @type {BABYLON.Observable}
  18346. */
  18347. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  18348. /**
  18349. * An event triggered after draw calls have been sent
  18350. * @type {BABYLON.Observable}
  18351. */
  18352. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  18353. /**
  18354. * An event triggered when physic simulation is about to be run
  18355. * @type {BABYLON.Observable}
  18356. */
  18357. this.onBeforePhysicsObservable = new BABYLON.Observable();
  18358. /**
  18359. * An event triggered when physic simulation has been done
  18360. * @type {BABYLON.Observable}
  18361. */
  18362. this.onAfterPhysicsObservable = new BABYLON.Observable();
  18363. /**
  18364. * An event triggered when the scene is ready
  18365. * @type {BABYLON.Observable}
  18366. */
  18367. this.onReadyObservable = new BABYLON.Observable();
  18368. /**
  18369. * An event triggered before rendering a camera
  18370. * @type {BABYLON.Observable}
  18371. */
  18372. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  18373. /**
  18374. * An event triggered after rendering a camera
  18375. * @type {BABYLON.Observable}
  18376. */
  18377. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  18378. /**
  18379. * An event triggered when active meshes evaluation is about to start
  18380. * @type {BABYLON.Observable}
  18381. */
  18382. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  18383. /**
  18384. * An event triggered when active meshes evaluation is done
  18385. * @type {BABYLON.Observable}
  18386. */
  18387. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  18388. /**
  18389. * An event triggered when particles rendering is about to start
  18390. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  18391. * @type {BABYLON.Observable}
  18392. */
  18393. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  18394. /**
  18395. * An event triggered when particles rendering is done
  18396. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  18397. * @type {BABYLON.Observable}
  18398. */
  18399. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  18400. /**
  18401. * An event triggered when sprites rendering is about to start
  18402. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  18403. * @type {BABYLON.Observable}
  18404. */
  18405. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  18406. /**
  18407. * An event triggered when sprites rendering is done
  18408. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  18409. * @type {BABYLON.Observable}
  18410. */
  18411. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  18412. /**
  18413. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  18414. * @type {BABYLON.Observable}
  18415. */
  18416. this.onDataLoadedObservable = new BABYLON.Observable();
  18417. /**
  18418. * An event triggered when a camera is created
  18419. * @type {BABYLON.Observable}
  18420. */
  18421. this.onNewCameraAddedObservable = new BABYLON.Observable();
  18422. /**
  18423. * An event triggered when a camera is removed
  18424. * @type {BABYLON.Observable}
  18425. */
  18426. this.onCameraRemovedObservable = new BABYLON.Observable();
  18427. /**
  18428. * An event triggered when a light is created
  18429. * @type {BABYLON.Observable}
  18430. */
  18431. this.onNewLightAddedObservable = new BABYLON.Observable();
  18432. /**
  18433. * An event triggered when a light is removed
  18434. * @type {BABYLON.Observable}
  18435. */
  18436. this.onLightRemovedObservable = new BABYLON.Observable();
  18437. /**
  18438. * An event triggered when a geometry is created
  18439. * @type {BABYLON.Observable}
  18440. */
  18441. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  18442. /**
  18443. * An event triggered when a geometry is removed
  18444. * @type {BABYLON.Observable}
  18445. */
  18446. this.onGeometryRemovedObservable = new BABYLON.Observable();
  18447. /**
  18448. * An event triggered when a transform node is created
  18449. * @type {BABYLON.Observable}
  18450. */
  18451. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  18452. /**
  18453. * An event triggered when a transform node is removed
  18454. * @type {BABYLON.Observable}
  18455. */
  18456. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  18457. /**
  18458. * An event triggered when a mesh is created
  18459. * @type {BABYLON.Observable}
  18460. */
  18461. this.onNewMeshAddedObservable = new BABYLON.Observable();
  18462. /**
  18463. * An event triggered when a mesh is removed
  18464. * @type {BABYLON.Observable}
  18465. */
  18466. this.onMeshRemovedObservable = new BABYLON.Observable();
  18467. /**
  18468. * An event triggered when render targets are about to be rendered
  18469. * Can happen multiple times per frame.
  18470. * @type {BABYLON.Observable}
  18471. */
  18472. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  18473. /**
  18474. * An event triggered when render targets were rendered.
  18475. * Can happen multiple times per frame.
  18476. * @type {BABYLON.Observable}
  18477. */
  18478. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  18479. /**
  18480. * An event triggered before calculating deterministic simulation step
  18481. * @type {BABYLON.Observable}
  18482. */
  18483. this.onBeforeStepObservable = new BABYLON.Observable();
  18484. /**
  18485. * An event triggered after calculating deterministic simulation step
  18486. * @type {BABYLON.Observable}
  18487. */
  18488. this.onAfterStepObservable = new BABYLON.Observable();
  18489. /**
  18490. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  18491. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  18492. * 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)
  18493. */
  18494. this.onRenderingGroupObservable = new BABYLON.Observable();
  18495. // Animations
  18496. this.animations = [];
  18497. /**
  18498. * 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).
  18499. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  18500. */
  18501. this.onPrePointerObservable = new BABYLON.Observable();
  18502. /**
  18503. * Observable event triggered each time an input event is received from the rendering canvas
  18504. */
  18505. this.onPointerObservable = new BABYLON.Observable();
  18506. this._meshPickProceed = false;
  18507. this._currentPickResult = null;
  18508. this._previousPickResult = null;
  18509. this._totalPointersPressed = 0;
  18510. this._doubleClickOccured = false;
  18511. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  18512. this.cameraToUseForPointers = null;
  18513. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  18514. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  18515. this._startingPointerTime = 0;
  18516. this._previousStartingPointerTime = 0;
  18517. // Deterministic lockstep
  18518. this._timeAccumulator = 0;
  18519. this._currentStepId = 0;
  18520. this._currentInternalStep = 0;
  18521. // Keyboard
  18522. /**
  18523. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  18524. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  18525. */
  18526. this.onPreKeyboardObservable = new BABYLON.Observable();
  18527. /**
  18528. * Observable event triggered each time an keyboard event is received from the hosting window
  18529. */
  18530. this.onKeyboardObservable = new BABYLON.Observable();
  18531. // Coordinate system
  18532. /**
  18533. * use right-handed coordinate system on this scene.
  18534. * @type {boolean}
  18535. */
  18536. this._useRightHandedSystem = false;
  18537. // Fog
  18538. this._fogEnabled = true;
  18539. this._fogMode = Scene.FOGMODE_NONE;
  18540. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  18541. this.fogDensity = 0.1;
  18542. this.fogStart = 0;
  18543. this.fogEnd = 1000.0;
  18544. // Lights
  18545. /**
  18546. * is shadow enabled on this scene.
  18547. * @type {boolean}
  18548. */
  18549. this._shadowsEnabled = true;
  18550. /**
  18551. * is light enabled on this scene.
  18552. * @type {boolean}
  18553. */
  18554. this._lightsEnabled = true;
  18555. /**
  18556. * All of the lights added to this scene.
  18557. * @see BABYLON.Light
  18558. * @type {BABYLON.Light[]}
  18559. */
  18560. this.lights = new Array();
  18561. // Cameras
  18562. /** All of the cameras added to this scene. */
  18563. this.cameras = new Array();
  18564. /** All of the active cameras added to this scene. */
  18565. this.activeCameras = new Array();
  18566. // Meshes
  18567. /**
  18568. * All of the tranform nodes added to this scene.
  18569. * @see BABYLON.TransformNode
  18570. * @type {BABYLON.TransformNode[]}
  18571. */
  18572. this.transformNodes = new Array();
  18573. /**
  18574. * All of the (abstract) meshes added to this scene.
  18575. * @see BABYLON.AbstractMesh
  18576. * @type {BABYLON.AbstractMesh[]}
  18577. */
  18578. this.meshes = new Array();
  18579. /**
  18580. * All of the animation groups added to this scene.
  18581. * @see BABYLON.AnimationGroup
  18582. * @type {BABYLON.AnimationGroup[]}
  18583. */
  18584. this.animationGroups = new Array();
  18585. // Geometries
  18586. this._geometries = new Array();
  18587. this.materials = new Array();
  18588. this.multiMaterials = new Array();
  18589. // Textures
  18590. this._texturesEnabled = true;
  18591. this.textures = new Array();
  18592. // Particles
  18593. this.particlesEnabled = true;
  18594. this.particleSystems = new Array();
  18595. // Sprites
  18596. this.spritesEnabled = true;
  18597. this.spriteManagers = new Array();
  18598. // Layers
  18599. this.layers = new Array();
  18600. this.highlightLayers = new Array();
  18601. // Skeletons
  18602. this._skeletonsEnabled = true;
  18603. this.skeletons = new Array();
  18604. // Morph targets
  18605. this.morphTargetManagers = new Array();
  18606. // Lens flares
  18607. this.lensFlaresEnabled = true;
  18608. this.lensFlareSystems = new Array();
  18609. // Collisions
  18610. this.collisionsEnabled = true;
  18611. /** Defines the gravity applied to this scene */
  18612. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  18613. // Postprocesses
  18614. this.postProcesses = new Array();
  18615. this.postProcessesEnabled = true;
  18616. // Customs render targets
  18617. this.renderTargetsEnabled = true;
  18618. this.dumpNextRenderTargets = false;
  18619. this.customRenderTargets = new Array();
  18620. // Imported meshes
  18621. this.importedMeshesFiles = new Array();
  18622. // Probes
  18623. this.probesEnabled = true;
  18624. this.reflectionProbes = new Array();
  18625. this._actionManagers = new Array();
  18626. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  18627. // Procedural textures
  18628. this.proceduralTexturesEnabled = true;
  18629. this._proceduralTextures = new Array();
  18630. this.soundTracks = new Array();
  18631. this._audioEnabled = true;
  18632. this._headphone = false;
  18633. // Performance counters
  18634. this._totalVertices = new BABYLON.PerfCounter();
  18635. this._activeIndices = new BABYLON.PerfCounter();
  18636. this._activeParticles = new BABYLON.PerfCounter();
  18637. this._activeBones = new BABYLON.PerfCounter();
  18638. this._animationTime = 0;
  18639. this.animationTimeScale = 1;
  18640. this._renderId = 0;
  18641. this._executeWhenReadyTimeoutId = -1;
  18642. this._intermediateRendering = false;
  18643. this._viewUpdateFlag = -1;
  18644. this._projectionUpdateFlag = -1;
  18645. this._alternateViewUpdateFlag = -1;
  18646. this._alternateProjectionUpdateFlag = -1;
  18647. this._toBeDisposed = new BABYLON.SmartArray(256);
  18648. this._activeRequests = new Array();
  18649. this._pendingData = new Array();
  18650. this._isDisposed = false;
  18651. this.dispatchAllSubMeshesOfActiveMeshes = false;
  18652. this._activeMeshes = new BABYLON.SmartArray(256);
  18653. this._processedMaterials = new BABYLON.SmartArray(256);
  18654. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  18655. this._activeParticleSystems = new BABYLON.SmartArray(256);
  18656. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  18657. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  18658. this._activeAnimatables = new Array();
  18659. this._transformMatrix = BABYLON.Matrix.Zero();
  18660. this._useAlternateCameraConfiguration = false;
  18661. this._alternateRendering = false;
  18662. this.requireLightSorting = false;
  18663. this._activeMeshesFrozen = false;
  18664. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  18665. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  18666. this._engine.scenes.push(this);
  18667. this._uid = null;
  18668. this._renderingManager = new BABYLON.RenderingManager(this);
  18669. this.postProcessManager = new BABYLON.PostProcessManager(this);
  18670. if (BABYLON.OutlineRenderer) {
  18671. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  18672. }
  18673. if (BABYLON.Tools.IsWindowObjectExist()) {
  18674. this.attachControl();
  18675. }
  18676. //simplification queue
  18677. if (BABYLON.SimplificationQueue) {
  18678. this.simplificationQueue = new BABYLON.SimplificationQueue();
  18679. }
  18680. //collision coordinator initialization. For now legacy per default.
  18681. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  18682. // Uniform Buffer
  18683. this._createUbo();
  18684. // Default Image processing definition.
  18685. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  18686. }
  18687. Object.defineProperty(Scene, "FOGMODE_NONE", {
  18688. /** The fog is deactivated */
  18689. get: function () {
  18690. return Scene._FOGMODE_NONE;
  18691. },
  18692. enumerable: true,
  18693. configurable: true
  18694. });
  18695. Object.defineProperty(Scene, "FOGMODE_EXP", {
  18696. /** The fog density is following an exponential function */
  18697. get: function () {
  18698. return Scene._FOGMODE_EXP;
  18699. },
  18700. enumerable: true,
  18701. configurable: true
  18702. });
  18703. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  18704. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  18705. get: function () {
  18706. return Scene._FOGMODE_EXP2;
  18707. },
  18708. enumerable: true,
  18709. configurable: true
  18710. });
  18711. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  18712. /** The fog density is following a linear function. */
  18713. get: function () {
  18714. return Scene._FOGMODE_LINEAR;
  18715. },
  18716. enumerable: true,
  18717. configurable: true
  18718. });
  18719. Object.defineProperty(Scene.prototype, "environmentTexture", {
  18720. /**
  18721. * Texture used in all pbr material as the reflection texture.
  18722. * As in the majority of the scene they are the same (exception for multi room and so on),
  18723. * this is easier to reference from here than from all the materials.
  18724. */
  18725. get: function () {
  18726. return this._environmentTexture;
  18727. },
  18728. /**
  18729. * Texture used in all pbr material as the reflection texture.
  18730. * As in the majority of the scene they are the same (exception for multi room and so on),
  18731. * this is easier to set here than in all the materials.
  18732. */
  18733. set: function (value) {
  18734. if (this._environmentTexture === value) {
  18735. return;
  18736. }
  18737. this._environmentTexture = value;
  18738. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18739. },
  18740. enumerable: true,
  18741. configurable: true
  18742. });
  18743. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  18744. /**
  18745. * Default image processing configuration used either in the rendering
  18746. * Forward main pass or through the imageProcessingPostProcess if present.
  18747. * As in the majority of the scene they are the same (exception for multi camera),
  18748. * this is easier to reference from here than from all the materials and post process.
  18749. *
  18750. * No setter as we it is a shared configuration, you can set the values instead.
  18751. */
  18752. get: function () {
  18753. return this._imageProcessingConfiguration;
  18754. },
  18755. enumerable: true,
  18756. configurable: true
  18757. });
  18758. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  18759. get: function () {
  18760. return this._forcePointsCloud;
  18761. },
  18762. set: function (value) {
  18763. if (this._forcePointsCloud === value) {
  18764. return;
  18765. }
  18766. this._forcePointsCloud = value;
  18767. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18768. },
  18769. enumerable: true,
  18770. configurable: true
  18771. });
  18772. Object.defineProperty(Scene.prototype, "onDispose", {
  18773. /** A function to be executed when this scene is disposed. */
  18774. set: function (callback) {
  18775. if (this._onDisposeObserver) {
  18776. this.onDisposeObservable.remove(this._onDisposeObserver);
  18777. }
  18778. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18779. },
  18780. enumerable: true,
  18781. configurable: true
  18782. });
  18783. Object.defineProperty(Scene.prototype, "beforeRender", {
  18784. /** A function to be executed before rendering this scene */
  18785. set: function (callback) {
  18786. if (this._onBeforeRenderObserver) {
  18787. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  18788. }
  18789. if (callback) {
  18790. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  18791. }
  18792. },
  18793. enumerable: true,
  18794. configurable: true
  18795. });
  18796. Object.defineProperty(Scene.prototype, "afterRender", {
  18797. /** A function to be executed after rendering this scene */
  18798. set: function (callback) {
  18799. if (this._onAfterRenderObserver) {
  18800. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  18801. }
  18802. if (callback) {
  18803. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  18804. }
  18805. },
  18806. enumerable: true,
  18807. configurable: true
  18808. });
  18809. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  18810. set: function (callback) {
  18811. if (this._onBeforeCameraRenderObserver) {
  18812. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  18813. }
  18814. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  18815. },
  18816. enumerable: true,
  18817. configurable: true
  18818. });
  18819. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  18820. set: function (callback) {
  18821. if (this._onAfterCameraRenderObserver) {
  18822. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  18823. }
  18824. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  18825. },
  18826. enumerable: true,
  18827. configurable: true
  18828. });
  18829. Object.defineProperty(Scene.prototype, "gamepadManager", {
  18830. get: function () {
  18831. if (!this._gamepadManager) {
  18832. this._gamepadManager = new BABYLON.GamepadManager(this);
  18833. }
  18834. return this._gamepadManager;
  18835. },
  18836. enumerable: true,
  18837. configurable: true
  18838. });
  18839. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  18840. get: function () {
  18841. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  18842. },
  18843. enumerable: true,
  18844. configurable: true
  18845. });
  18846. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  18847. get: function () {
  18848. return this._useRightHandedSystem;
  18849. },
  18850. set: function (value) {
  18851. if (this._useRightHandedSystem === value) {
  18852. return;
  18853. }
  18854. this._useRightHandedSystem = value;
  18855. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18856. },
  18857. enumerable: true,
  18858. configurable: true
  18859. });
  18860. Scene.prototype.setStepId = function (newStepId) {
  18861. this._currentStepId = newStepId;
  18862. };
  18863. ;
  18864. Scene.prototype.getStepId = function () {
  18865. return this._currentStepId;
  18866. };
  18867. ;
  18868. Scene.prototype.getInternalStep = function () {
  18869. return this._currentInternalStep;
  18870. };
  18871. ;
  18872. Object.defineProperty(Scene.prototype, "fogEnabled", {
  18873. get: function () {
  18874. return this._fogEnabled;
  18875. },
  18876. /**
  18877. * is fog enabled on this scene.
  18878. */
  18879. set: function (value) {
  18880. if (this._fogEnabled === value) {
  18881. return;
  18882. }
  18883. this._fogEnabled = value;
  18884. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18885. },
  18886. enumerable: true,
  18887. configurable: true
  18888. });
  18889. Object.defineProperty(Scene.prototype, "fogMode", {
  18890. get: function () {
  18891. return this._fogMode;
  18892. },
  18893. set: function (value) {
  18894. if (this._fogMode === value) {
  18895. return;
  18896. }
  18897. this._fogMode = value;
  18898. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18899. },
  18900. enumerable: true,
  18901. configurable: true
  18902. });
  18903. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  18904. get: function () {
  18905. return this._shadowsEnabled;
  18906. },
  18907. set: function (value) {
  18908. if (this._shadowsEnabled === value) {
  18909. return;
  18910. }
  18911. this._shadowsEnabled = value;
  18912. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  18913. },
  18914. enumerable: true,
  18915. configurable: true
  18916. });
  18917. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  18918. get: function () {
  18919. return this._lightsEnabled;
  18920. },
  18921. set: function (value) {
  18922. if (this._lightsEnabled === value) {
  18923. return;
  18924. }
  18925. this._lightsEnabled = value;
  18926. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  18927. },
  18928. enumerable: true,
  18929. configurable: true
  18930. });
  18931. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  18932. /** The default material used on meshes when no material is affected */
  18933. get: function () {
  18934. if (!this._defaultMaterial) {
  18935. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  18936. }
  18937. return this._defaultMaterial;
  18938. },
  18939. /** The default material used on meshes when no material is affected */
  18940. set: function (value) {
  18941. this._defaultMaterial = value;
  18942. },
  18943. enumerable: true,
  18944. configurable: true
  18945. });
  18946. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  18947. get: function () {
  18948. return this._texturesEnabled;
  18949. },
  18950. set: function (value) {
  18951. if (this._texturesEnabled === value) {
  18952. return;
  18953. }
  18954. this._texturesEnabled = value;
  18955. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18956. },
  18957. enumerable: true,
  18958. configurable: true
  18959. });
  18960. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  18961. get: function () {
  18962. return this._skeletonsEnabled;
  18963. },
  18964. set: function (value) {
  18965. if (this._skeletonsEnabled === value) {
  18966. return;
  18967. }
  18968. this._skeletonsEnabled = value;
  18969. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  18970. },
  18971. enumerable: true,
  18972. configurable: true
  18973. });
  18974. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  18975. get: function () {
  18976. if (!this._postProcessRenderPipelineManager) {
  18977. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  18978. }
  18979. return this._postProcessRenderPipelineManager;
  18980. },
  18981. enumerable: true,
  18982. configurable: true
  18983. });
  18984. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  18985. get: function () {
  18986. if (!this._mainSoundTrack) {
  18987. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  18988. }
  18989. return this._mainSoundTrack;
  18990. },
  18991. enumerable: true,
  18992. configurable: true
  18993. });
  18994. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  18995. get: function () {
  18996. return this._alternateRendering;
  18997. },
  18998. enumerable: true,
  18999. configurable: true
  19000. });
  19001. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  19002. get: function () {
  19003. return this._frustumPlanes;
  19004. },
  19005. enumerable: true,
  19006. configurable: true
  19007. });
  19008. Object.defineProperty(Scene.prototype, "debugLayer", {
  19009. // Properties
  19010. get: function () {
  19011. if (!this._debugLayer) {
  19012. this._debugLayer = new BABYLON.DebugLayer(this);
  19013. }
  19014. return this._debugLayer;
  19015. },
  19016. enumerable: true,
  19017. configurable: true
  19018. });
  19019. Object.defineProperty(Scene.prototype, "workerCollisions", {
  19020. get: function () {
  19021. return this._workerCollisions;
  19022. },
  19023. set: function (enabled) {
  19024. if (!BABYLON.CollisionCoordinatorLegacy) {
  19025. return;
  19026. }
  19027. enabled = (enabled && !!Worker);
  19028. this._workerCollisions = enabled;
  19029. if (this.collisionCoordinator) {
  19030. this.collisionCoordinator.destroy();
  19031. }
  19032. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  19033. this.collisionCoordinator.init(this);
  19034. },
  19035. enumerable: true,
  19036. configurable: true
  19037. });
  19038. Object.defineProperty(Scene.prototype, "selectionOctree", {
  19039. get: function () {
  19040. return this._selectionOctree;
  19041. },
  19042. enumerable: true,
  19043. configurable: true
  19044. });
  19045. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  19046. /**
  19047. * The mesh that is currently under the pointer.
  19048. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  19049. */
  19050. get: function () {
  19051. return this._pointerOverMesh;
  19052. },
  19053. enumerable: true,
  19054. configurable: true
  19055. });
  19056. Object.defineProperty(Scene.prototype, "pointerX", {
  19057. /**
  19058. * Current on-screen X position of the pointer
  19059. * @return {number} X position of the pointer
  19060. */
  19061. get: function () {
  19062. return this._pointerX;
  19063. },
  19064. enumerable: true,
  19065. configurable: true
  19066. });
  19067. Object.defineProperty(Scene.prototype, "pointerY", {
  19068. /**
  19069. * Current on-screen Y position of the pointer
  19070. * @return {number} Y position of the pointer
  19071. */
  19072. get: function () {
  19073. return this._pointerY;
  19074. },
  19075. enumerable: true,
  19076. configurable: true
  19077. });
  19078. Scene.prototype.getCachedMaterial = function () {
  19079. return this._cachedMaterial;
  19080. };
  19081. Scene.prototype.getCachedEffect = function () {
  19082. return this._cachedEffect;
  19083. };
  19084. Scene.prototype.getCachedVisibility = function () {
  19085. return this._cachedVisibility;
  19086. };
  19087. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  19088. if (visibility === void 0) { visibility = 1; }
  19089. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  19090. };
  19091. Scene.prototype.getBoundingBoxRenderer = function () {
  19092. if (!this._boundingBoxRenderer) {
  19093. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  19094. }
  19095. return this._boundingBoxRenderer;
  19096. };
  19097. Scene.prototype.getOutlineRenderer = function () {
  19098. return this._outlineRenderer;
  19099. };
  19100. Scene.prototype.getEngine = function () {
  19101. return this._engine;
  19102. };
  19103. Scene.prototype.getTotalVertices = function () {
  19104. return this._totalVertices.current;
  19105. };
  19106. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  19107. get: function () {
  19108. return this._totalVertices;
  19109. },
  19110. enumerable: true,
  19111. configurable: true
  19112. });
  19113. Scene.prototype.getActiveIndices = function () {
  19114. return this._activeIndices.current;
  19115. };
  19116. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  19117. get: function () {
  19118. return this._activeIndices;
  19119. },
  19120. enumerable: true,
  19121. configurable: true
  19122. });
  19123. Scene.prototype.getActiveParticles = function () {
  19124. return this._activeParticles.current;
  19125. };
  19126. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  19127. get: function () {
  19128. return this._activeParticles;
  19129. },
  19130. enumerable: true,
  19131. configurable: true
  19132. });
  19133. Scene.prototype.getActiveBones = function () {
  19134. return this._activeBones.current;
  19135. };
  19136. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  19137. get: function () {
  19138. return this._activeBones;
  19139. },
  19140. enumerable: true,
  19141. configurable: true
  19142. });
  19143. // Stats
  19144. Scene.prototype.getInterFramePerfCounter = function () {
  19145. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  19146. return 0;
  19147. };
  19148. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  19149. get: function () {
  19150. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  19151. return null;
  19152. },
  19153. enumerable: true,
  19154. configurable: true
  19155. });
  19156. Scene.prototype.getLastFrameDuration = function () {
  19157. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  19158. return 0;
  19159. };
  19160. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  19161. get: function () {
  19162. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  19163. return null;
  19164. },
  19165. enumerable: true,
  19166. configurable: true
  19167. });
  19168. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  19169. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  19170. return 0;
  19171. };
  19172. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  19173. get: function () {
  19174. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  19175. return null;
  19176. },
  19177. enumerable: true,
  19178. configurable: true
  19179. });
  19180. Scene.prototype.getActiveMeshes = function () {
  19181. return this._activeMeshes;
  19182. };
  19183. Scene.prototype.getRenderTargetsDuration = function () {
  19184. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  19185. return 0;
  19186. };
  19187. Scene.prototype.getRenderDuration = function () {
  19188. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  19189. return 0;
  19190. };
  19191. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  19192. get: function () {
  19193. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  19194. return null;
  19195. },
  19196. enumerable: true,
  19197. configurable: true
  19198. });
  19199. Scene.prototype.getParticlesDuration = function () {
  19200. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  19201. return 0;
  19202. };
  19203. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  19204. get: function () {
  19205. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  19206. return null;
  19207. },
  19208. enumerable: true,
  19209. configurable: true
  19210. });
  19211. Scene.prototype.getSpritesDuration = function () {
  19212. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  19213. return 0;
  19214. };
  19215. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  19216. get: function () {
  19217. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  19218. return null;
  19219. },
  19220. enumerable: true,
  19221. configurable: true
  19222. });
  19223. Scene.prototype.getAnimationRatio = function () {
  19224. return this._animationRatio;
  19225. };
  19226. Scene.prototype.getRenderId = function () {
  19227. return this._renderId;
  19228. };
  19229. Scene.prototype.incrementRenderId = function () {
  19230. this._renderId++;
  19231. };
  19232. Scene.prototype._updatePointerPosition = function (evt) {
  19233. var canvasRect = this._engine.getRenderingCanvasClientRect();
  19234. if (!canvasRect) {
  19235. return;
  19236. }
  19237. this._pointerX = evt.clientX - canvasRect.left;
  19238. this._pointerY = evt.clientY - canvasRect.top;
  19239. this._unTranslatedPointerX = this._pointerX;
  19240. this._unTranslatedPointerY = this._pointerY;
  19241. };
  19242. Scene.prototype._createUbo = function () {
  19243. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  19244. this._sceneUbo.addUniform("viewProjection", 16);
  19245. this._sceneUbo.addUniform("view", 16);
  19246. };
  19247. Scene.prototype._createAlternateUbo = function () {
  19248. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  19249. this._alternateSceneUbo.addUniform("viewProjection", 16);
  19250. this._alternateSceneUbo.addUniform("view", 16);
  19251. };
  19252. // Pointers handling
  19253. /**
  19254. * Use this method to simulate a pointer move on a mesh
  19255. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  19256. */
  19257. Scene.prototype.simulatePointerMove = function (pickResult) {
  19258. var evt = new PointerEvent("pointermove");
  19259. return this._processPointerMove(pickResult, evt);
  19260. };
  19261. Scene.prototype._processPointerMove = function (pickResult, evt) {
  19262. var canvas = this._engine.getRenderingCanvas();
  19263. if (!canvas) {
  19264. return this;
  19265. }
  19266. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  19267. this.setPointerOverSprite(null);
  19268. this.setPointerOverMesh(pickResult.pickedMesh);
  19269. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  19270. if (this._pointerOverMesh.actionManager.hoverCursor) {
  19271. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  19272. }
  19273. else {
  19274. canvas.style.cursor = this.hoverCursor;
  19275. }
  19276. }
  19277. else {
  19278. canvas.style.cursor = this.defaultCursor;
  19279. }
  19280. }
  19281. else {
  19282. this.setPointerOverMesh(null);
  19283. // Sprites
  19284. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  19285. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  19286. this.setPointerOverSprite(pickResult.pickedSprite);
  19287. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  19288. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  19289. }
  19290. else {
  19291. canvas.style.cursor = this.hoverCursor;
  19292. }
  19293. }
  19294. else {
  19295. this.setPointerOverSprite(null);
  19296. // Restore pointer
  19297. canvas.style.cursor = this.defaultCursor;
  19298. }
  19299. }
  19300. if (pickResult) {
  19301. if (this.onPointerMove) {
  19302. this.onPointerMove(evt, pickResult);
  19303. }
  19304. if (this.onPointerObservable.hasObservers()) {
  19305. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  19306. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  19307. this.onPointerObservable.notifyObservers(pi, type);
  19308. }
  19309. }
  19310. return this;
  19311. };
  19312. /**
  19313. * Use this method to simulate a pointer down on a mesh
  19314. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  19315. */
  19316. Scene.prototype.simulatePointerDown = function (pickResult) {
  19317. var evt = new PointerEvent("pointerdown");
  19318. return this._processPointerDown(pickResult, evt);
  19319. };
  19320. Scene.prototype._processPointerDown = function (pickResult, evt) {
  19321. var _this = this;
  19322. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  19323. this._pickedDownMesh = pickResult.pickedMesh;
  19324. var actionManager = pickResult.pickedMesh.actionManager;
  19325. if (actionManager) {
  19326. if (actionManager.hasPickTriggers) {
  19327. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19328. switch (evt.button) {
  19329. case 0:
  19330. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19331. break;
  19332. case 1:
  19333. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19334. break;
  19335. case 2:
  19336. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19337. break;
  19338. }
  19339. }
  19340. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  19341. window.setTimeout(function () {
  19342. 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);
  19343. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  19344. if (_this._totalPointersPressed !== 0 &&
  19345. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  19346. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  19347. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  19348. _this._startingPointerTime = 0;
  19349. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19350. }
  19351. }
  19352. }, Scene.LongPressDelay);
  19353. }
  19354. }
  19355. }
  19356. if (pickResult) {
  19357. if (this.onPointerDown) {
  19358. this.onPointerDown(evt, pickResult);
  19359. }
  19360. if (this.onPointerObservable.hasObservers()) {
  19361. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  19362. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  19363. this.onPointerObservable.notifyObservers(pi, type);
  19364. }
  19365. }
  19366. return this;
  19367. };
  19368. /**
  19369. * Use this method to simulate a pointer up on a mesh
  19370. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  19371. */
  19372. Scene.prototype.simulatePointerUp = function (pickResult) {
  19373. var evt = new PointerEvent("pointerup");
  19374. var clickInfo = new ClickInfo();
  19375. clickInfo.singleClick = true;
  19376. clickInfo.ignore = true;
  19377. return this._processPointerUp(pickResult, evt, clickInfo);
  19378. };
  19379. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  19380. if (pickResult && pickResult && pickResult.pickedMesh) {
  19381. this._pickedUpMesh = pickResult.pickedMesh;
  19382. if (this._pickedDownMesh === this._pickedUpMesh) {
  19383. if (this.onPointerPick) {
  19384. this.onPointerPick(evt, pickResult);
  19385. }
  19386. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  19387. var type = BABYLON.PointerEventTypes.POINTERPICK;
  19388. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  19389. this.onPointerObservable.notifyObservers(pi, type);
  19390. }
  19391. }
  19392. if (pickResult.pickedMesh.actionManager) {
  19393. if (clickInfo.ignore) {
  19394. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19395. }
  19396. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  19397. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19398. }
  19399. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  19400. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19401. }
  19402. }
  19403. }
  19404. if (this._pickedDownMesh &&
  19405. this._pickedDownMesh.actionManager &&
  19406. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  19407. this._pickedDownMesh !== this._pickedUpMesh) {
  19408. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  19409. }
  19410. if (this.onPointerUp) {
  19411. this.onPointerUp(evt, pickResult);
  19412. }
  19413. if (this.onPointerObservable.hasObservers()) {
  19414. if (!clickInfo.ignore) {
  19415. if (!clickInfo.hasSwiped) {
  19416. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  19417. var type = BABYLON.PointerEventTypes.POINTERTAP;
  19418. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  19419. this.onPointerObservable.notifyObservers(pi, type);
  19420. }
  19421. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  19422. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  19423. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  19424. this.onPointerObservable.notifyObservers(pi, type);
  19425. }
  19426. }
  19427. }
  19428. else {
  19429. var type = BABYLON.PointerEventTypes.POINTERUP;
  19430. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  19431. this.onPointerObservable.notifyObservers(pi, type);
  19432. }
  19433. }
  19434. return this;
  19435. };
  19436. /**
  19437. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  19438. * @param attachUp defines if you want to attach events to pointerup
  19439. * @param attachDown defines if you want to attach events to pointerdown
  19440. * @param attachMove defines if you want to attach events to pointermove
  19441. */
  19442. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  19443. var _this = this;
  19444. if (attachUp === void 0) { attachUp = true; }
  19445. if (attachDown === void 0) { attachDown = true; }
  19446. if (attachMove === void 0) { attachMove = true; }
  19447. this._initActionManager = function (act, clickInfo) {
  19448. if (!_this._meshPickProceed) {
  19449. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  19450. _this._currentPickResult = pickResult;
  19451. if (pickResult) {
  19452. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  19453. }
  19454. _this._meshPickProceed = true;
  19455. }
  19456. return act;
  19457. };
  19458. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  19459. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  19460. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  19461. btn !== _this._previousButtonPressed) {
  19462. _this._doubleClickOccured = false;
  19463. clickInfo.singleClick = true;
  19464. clickInfo.ignore = false;
  19465. cb(clickInfo, _this._currentPickResult);
  19466. }
  19467. };
  19468. this._initClickEvent = function (obs1, obs2, evt, cb) {
  19469. var clickInfo = new ClickInfo();
  19470. _this._currentPickResult = null;
  19471. var act = null;
  19472. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  19473. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  19474. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  19475. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  19476. act = _this._initActionManager(act, clickInfo);
  19477. if (act)
  19478. checkPicking = act.hasPickTriggers;
  19479. }
  19480. if (checkPicking) {
  19481. var btn = evt.button;
  19482. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  19483. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  19484. if (!clickInfo.hasSwiped) {
  19485. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  19486. if (!checkSingleClickImmediately) {
  19487. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  19488. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  19489. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  19490. act = _this._initActionManager(act, clickInfo);
  19491. if (act)
  19492. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  19493. }
  19494. }
  19495. if (checkSingleClickImmediately) {
  19496. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  19497. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  19498. btn !== _this._previousButtonPressed) {
  19499. clickInfo.singleClick = true;
  19500. cb(clickInfo, _this._currentPickResult);
  19501. }
  19502. }
  19503. else {
  19504. // wait that no double click has been raised during the double click delay
  19505. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  19506. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  19507. }
  19508. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  19509. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  19510. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  19511. act = _this._initActionManager(act, clickInfo);
  19512. if (act)
  19513. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  19514. }
  19515. if (checkDoubleClick) {
  19516. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  19517. if (btn === _this._previousButtonPressed &&
  19518. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  19519. !_this._doubleClickOccured) {
  19520. // pointer has not moved for 2 clicks, it's a double click
  19521. if (!clickInfo.hasSwiped &&
  19522. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  19523. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  19524. _this._previousStartingPointerTime = 0;
  19525. _this._doubleClickOccured = true;
  19526. clickInfo.doubleClick = true;
  19527. clickInfo.ignore = false;
  19528. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  19529. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  19530. }
  19531. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  19532. cb(clickInfo, _this._currentPickResult);
  19533. }
  19534. else {
  19535. _this._doubleClickOccured = false;
  19536. _this._previousStartingPointerTime = _this._startingPointerTime;
  19537. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  19538. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  19539. _this._previousButtonPressed = btn;
  19540. if (Scene.ExclusiveDoubleClickMode) {
  19541. if (_this._previousDelayedSimpleClickTimeout) {
  19542. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  19543. }
  19544. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  19545. cb(clickInfo, _this._previousPickResult);
  19546. }
  19547. else {
  19548. cb(clickInfo, _this._currentPickResult);
  19549. }
  19550. }
  19551. }
  19552. else {
  19553. _this._doubleClickOccured = false;
  19554. _this._previousStartingPointerTime = _this._startingPointerTime;
  19555. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  19556. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  19557. _this._previousButtonPressed = btn;
  19558. }
  19559. }
  19560. }
  19561. }
  19562. clickInfo.ignore = true;
  19563. cb(clickInfo, _this._currentPickResult);
  19564. };
  19565. this._spritePredicate = function (sprite) {
  19566. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  19567. };
  19568. this._onPointerMove = function (evt) {
  19569. _this._updatePointerPosition(evt);
  19570. // PreObservable support
  19571. if (_this.onPrePointerObservable.hasObservers()) {
  19572. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  19573. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19574. _this.onPrePointerObservable.notifyObservers(pi, type);
  19575. if (pi.skipOnPointerObservable) {
  19576. return;
  19577. }
  19578. }
  19579. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  19580. return;
  19581. }
  19582. if (!_this.pointerMovePredicate) {
  19583. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  19584. }
  19585. // Meshes
  19586. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  19587. _this._processPointerMove(pickResult, evt);
  19588. };
  19589. this._onPointerDown = function (evt) {
  19590. _this._totalPointersPressed++;
  19591. _this._pickedDownMesh = null;
  19592. _this._meshPickProceed = false;
  19593. _this._updatePointerPosition(evt);
  19594. if (_this.preventDefaultOnPointerDown && canvas) {
  19595. evt.preventDefault();
  19596. canvas.focus();
  19597. }
  19598. // PreObservable support
  19599. if (_this.onPrePointerObservable.hasObservers()) {
  19600. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  19601. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19602. _this.onPrePointerObservable.notifyObservers(pi, type);
  19603. if (pi.skipOnPointerObservable) {
  19604. return;
  19605. }
  19606. }
  19607. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  19608. return;
  19609. }
  19610. _this._startingPointerPosition.x = _this._pointerX;
  19611. _this._startingPointerPosition.y = _this._pointerY;
  19612. _this._startingPointerTime = new Date().getTime();
  19613. if (!_this.pointerDownPredicate) {
  19614. _this.pointerDownPredicate = function (mesh) {
  19615. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  19616. };
  19617. }
  19618. // Meshes
  19619. _this._pickedDownMesh = null;
  19620. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  19621. _this._processPointerDown(pickResult, evt);
  19622. // Sprites
  19623. _this._pickedDownSprite = null;
  19624. if (_this.spriteManagers.length > 0) {
  19625. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  19626. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  19627. if (pickResult.pickedSprite.actionManager) {
  19628. _this._pickedDownSprite = pickResult.pickedSprite;
  19629. switch (evt.button) {
  19630. case 0:
  19631. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19632. break;
  19633. case 1:
  19634. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19635. break;
  19636. case 2:
  19637. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19638. break;
  19639. }
  19640. if (pickResult.pickedSprite.actionManager) {
  19641. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19642. }
  19643. }
  19644. }
  19645. }
  19646. };
  19647. this._onPointerUp = function (evt) {
  19648. if (_this._totalPointersPressed === 0) {
  19649. return; // So we need to test it the pointer down was pressed before.
  19650. }
  19651. _this._totalPointersPressed--;
  19652. _this._pickedUpMesh = null;
  19653. _this._meshPickProceed = false;
  19654. _this._updatePointerPosition(evt);
  19655. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  19656. // PreObservable support
  19657. if (_this.onPrePointerObservable.hasObservers()) {
  19658. if (!clickInfo.ignore) {
  19659. if (!clickInfo.hasSwiped) {
  19660. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  19661. var type = BABYLON.PointerEventTypes.POINTERTAP;
  19662. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19663. _this.onPrePointerObservable.notifyObservers(pi, type);
  19664. if (pi.skipOnPointerObservable) {
  19665. return;
  19666. }
  19667. }
  19668. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  19669. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  19670. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19671. _this.onPrePointerObservable.notifyObservers(pi, type);
  19672. if (pi.skipOnPointerObservable) {
  19673. return;
  19674. }
  19675. }
  19676. }
  19677. }
  19678. else {
  19679. var type = BABYLON.PointerEventTypes.POINTERUP;
  19680. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19681. _this.onPrePointerObservable.notifyObservers(pi, type);
  19682. if (pi.skipOnPointerObservable) {
  19683. return;
  19684. }
  19685. }
  19686. }
  19687. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  19688. return;
  19689. }
  19690. if (!_this.pointerUpPredicate) {
  19691. _this.pointerUpPredicate = function (mesh) {
  19692. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  19693. };
  19694. }
  19695. // Meshes
  19696. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  19697. _this._initActionManager(null, clickInfo);
  19698. }
  19699. if (!pickResult) {
  19700. pickResult = _this._currentPickResult;
  19701. }
  19702. _this._processPointerUp(pickResult, evt, clickInfo);
  19703. // Sprites
  19704. if (_this.spriteManagers.length > 0) {
  19705. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  19706. if (spritePickResult) {
  19707. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  19708. if (spritePickResult.pickedSprite.actionManager) {
  19709. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  19710. if (spritePickResult.pickedSprite.actionManager) {
  19711. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  19712. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  19713. }
  19714. }
  19715. }
  19716. }
  19717. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  19718. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  19719. }
  19720. }
  19721. }
  19722. _this._previousPickResult = _this._currentPickResult;
  19723. });
  19724. };
  19725. this._onKeyDown = function (evt) {
  19726. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  19727. if (_this.onPreKeyboardObservable.hasObservers()) {
  19728. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  19729. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  19730. if (pi.skipOnPointerObservable) {
  19731. return;
  19732. }
  19733. }
  19734. if (_this.onKeyboardObservable.hasObservers()) {
  19735. var pi = new BABYLON.KeyboardInfo(type, evt);
  19736. _this.onKeyboardObservable.notifyObservers(pi, type);
  19737. }
  19738. if (_this.actionManager) {
  19739. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  19740. }
  19741. };
  19742. this._onKeyUp = function (evt) {
  19743. var type = BABYLON.KeyboardEventTypes.KEYUP;
  19744. if (_this.onPreKeyboardObservable.hasObservers()) {
  19745. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  19746. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  19747. if (pi.skipOnPointerObservable) {
  19748. return;
  19749. }
  19750. }
  19751. if (_this.onKeyboardObservable.hasObservers()) {
  19752. var pi = new BABYLON.KeyboardInfo(type, evt);
  19753. _this.onKeyboardObservable.notifyObservers(pi, type);
  19754. }
  19755. if (_this.actionManager) {
  19756. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  19757. }
  19758. };
  19759. var engine = this.getEngine();
  19760. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  19761. if (!canvas) {
  19762. return;
  19763. }
  19764. canvas.addEventListener("keydown", _this._onKeyDown, false);
  19765. canvas.addEventListener("keyup", _this._onKeyUp, false);
  19766. });
  19767. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  19768. if (!canvas) {
  19769. return;
  19770. }
  19771. canvas.removeEventListener("keydown", _this._onKeyDown);
  19772. canvas.removeEventListener("keyup", _this._onKeyUp);
  19773. });
  19774. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  19775. var canvas = this._engine.getRenderingCanvas();
  19776. if (!canvas) {
  19777. return;
  19778. }
  19779. if (attachMove) {
  19780. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  19781. // Wheel
  19782. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  19783. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  19784. }
  19785. if (attachDown) {
  19786. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  19787. }
  19788. if (attachUp) {
  19789. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  19790. }
  19791. canvas.tabIndex = 1;
  19792. };
  19793. Scene.prototype.detachControl = function () {
  19794. var engine = this.getEngine();
  19795. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  19796. var canvas = engine.getRenderingCanvas();
  19797. if (!canvas) {
  19798. return;
  19799. }
  19800. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  19801. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  19802. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  19803. if (this._onCanvasBlurObserver) {
  19804. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  19805. }
  19806. if (this._onCanvasFocusObserver) {
  19807. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  19808. }
  19809. // Wheel
  19810. canvas.removeEventListener('mousewheel', this._onPointerMove);
  19811. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  19812. // Keyboard
  19813. canvas.removeEventListener("keydown", this._onKeyDown);
  19814. canvas.removeEventListener("keyup", this._onKeyUp);
  19815. // Observables
  19816. this.onKeyboardObservable.clear();
  19817. this.onPreKeyboardObservable.clear();
  19818. this.onPointerObservable.clear();
  19819. this.onPrePointerObservable.clear();
  19820. };
  19821. // Ready
  19822. Scene.prototype.isReady = function () {
  19823. if (this._isDisposed) {
  19824. return false;
  19825. }
  19826. if (this._pendingData.length > 0) {
  19827. return false;
  19828. }
  19829. var index;
  19830. // Geometries
  19831. for (index = 0; index < this._geometries.length; index++) {
  19832. var geometry = this._geometries[index];
  19833. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19834. return false;
  19835. }
  19836. }
  19837. // Meshes
  19838. for (index = 0; index < this.meshes.length; index++) {
  19839. var mesh = this.meshes[index];
  19840. if (!mesh.isEnabled()) {
  19841. continue;
  19842. }
  19843. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  19844. continue;
  19845. }
  19846. if (!mesh.isReady()) {
  19847. return false;
  19848. }
  19849. var mat = mesh.material;
  19850. if (mat) {
  19851. if (!mat.isReady(mesh)) {
  19852. return false;
  19853. }
  19854. }
  19855. }
  19856. return true;
  19857. };
  19858. Scene.prototype.resetCachedMaterial = function () {
  19859. this._cachedMaterial = null;
  19860. this._cachedEffect = null;
  19861. this._cachedVisibility = null;
  19862. };
  19863. Scene.prototype.registerBeforeRender = function (func) {
  19864. this.onBeforeRenderObservable.add(func);
  19865. };
  19866. Scene.prototype.unregisterBeforeRender = function (func) {
  19867. this.onBeforeRenderObservable.removeCallback(func);
  19868. };
  19869. Scene.prototype.registerAfterRender = function (func) {
  19870. this.onAfterRenderObservable.add(func);
  19871. };
  19872. Scene.prototype.unregisterAfterRender = function (func) {
  19873. this.onAfterRenderObservable.removeCallback(func);
  19874. };
  19875. Scene.prototype._addPendingData = function (data) {
  19876. this._pendingData.push(data);
  19877. };
  19878. Scene.prototype._removePendingData = function (data) {
  19879. var wasLoading = this.isLoading;
  19880. var index = this._pendingData.indexOf(data);
  19881. if (index !== -1) {
  19882. this._pendingData.splice(index, 1);
  19883. }
  19884. if (wasLoading && !this.isLoading) {
  19885. this.onDataLoadedObservable.notifyObservers(this);
  19886. }
  19887. };
  19888. Scene.prototype.getWaitingItemsCount = function () {
  19889. return this._pendingData.length;
  19890. };
  19891. Object.defineProperty(Scene.prototype, "isLoading", {
  19892. get: function () {
  19893. return this._pendingData.length > 0;
  19894. },
  19895. enumerable: true,
  19896. configurable: true
  19897. });
  19898. /**
  19899. * Registers a function to be executed when the scene is ready.
  19900. * @param {Function} func - the function to be executed.
  19901. */
  19902. Scene.prototype.executeWhenReady = function (func) {
  19903. var _this = this;
  19904. this.onReadyObservable.add(func);
  19905. if (this._executeWhenReadyTimeoutId !== -1) {
  19906. return;
  19907. }
  19908. this._executeWhenReadyTimeoutId = setTimeout(function () {
  19909. _this._checkIsReady();
  19910. }, 150);
  19911. };
  19912. Scene.prototype._checkIsReady = function () {
  19913. var _this = this;
  19914. if (this.isReady()) {
  19915. this.onReadyObservable.notifyObservers(this);
  19916. this.onReadyObservable.clear();
  19917. this._executeWhenReadyTimeoutId = -1;
  19918. return;
  19919. }
  19920. this._executeWhenReadyTimeoutId = setTimeout(function () {
  19921. _this._checkIsReady();
  19922. }, 150);
  19923. };
  19924. // Animations
  19925. /**
  19926. * Will start the animation sequence of a given target
  19927. * @param target - the target
  19928. * @param {number} from - from which frame should animation start
  19929. * @param {number} to - till which frame should animation run.
  19930. * @param {boolean} [loop] - should the animation loop
  19931. * @param {number} [speedRatio] - the speed in which to run the animation
  19932. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  19933. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  19934. * Returns {BABYLON.Animatable} the animatable object created for this animation
  19935. * See BABYLON.Animatable
  19936. */
  19937. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  19938. if (speedRatio === void 0) { speedRatio = 1.0; }
  19939. if (from > to && speedRatio > 0) {
  19940. speedRatio *= -1;
  19941. }
  19942. this.stopAnimation(target);
  19943. if (!animatable) {
  19944. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  19945. }
  19946. // Local animations
  19947. if (target.animations) {
  19948. animatable.appendAnimations(target, target.animations);
  19949. }
  19950. // Children animations
  19951. if (target.getAnimatables) {
  19952. var animatables = target.getAnimatables();
  19953. for (var index = 0; index < animatables.length; index++) {
  19954. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  19955. }
  19956. }
  19957. animatable.reset();
  19958. return animatable;
  19959. };
  19960. /**
  19961. * Begin a new animation on a given node
  19962. * @param {BABYLON.Node} node defines the root node where the animation will take place
  19963. * @param {BABYLON.Animation[]} defines the list of animations to start
  19964. * @param {number} from defines the initial value
  19965. * @param {number} to defines the final value
  19966. * @param {boolean} loop defines if you want animation to loop (off by default)
  19967. * @param {number} speedRatio defines the speed ratio to apply to all animations
  19968. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  19969. * @returns the list of created animatables
  19970. */
  19971. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  19972. if (speedRatio === undefined) {
  19973. speedRatio = 1.0;
  19974. }
  19975. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  19976. return animatable;
  19977. };
  19978. /**
  19979. * Begin a new animation on a given node and its hierarchy
  19980. * @param {BABYLON.Node} node defines the root node where the animation will take place
  19981. * @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.
  19982. * @param {BABYLON.Animation[]} defines the list of animations to start
  19983. * @param {number} from defines the initial value
  19984. * @param {number} to defines the final value
  19985. * @param {boolean} loop defines if you want animation to loop (off by default)
  19986. * @param {number} speedRatio defines the speed ratio to apply to all animations
  19987. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  19988. * @returns the list of animatables created for all nodes
  19989. */
  19990. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  19991. var children = target.getDescendants(directDescendantsOnly);
  19992. var result = [];
  19993. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  19994. var child = children_1[_i];
  19995. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  19996. }
  19997. return result;
  19998. };
  19999. Scene.prototype.getAnimatableByTarget = function (target) {
  20000. for (var index = 0; index < this._activeAnimatables.length; index++) {
  20001. if (this._activeAnimatables[index].target === target) {
  20002. return this._activeAnimatables[index];
  20003. }
  20004. }
  20005. return null;
  20006. };
  20007. Object.defineProperty(Scene.prototype, "animatables", {
  20008. get: function () {
  20009. return this._activeAnimatables;
  20010. },
  20011. enumerable: true,
  20012. configurable: true
  20013. });
  20014. /**
  20015. * Will stop the animation of the given target
  20016. * @param target - the target
  20017. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  20018. * @see beginAnimation
  20019. */
  20020. Scene.prototype.stopAnimation = function (target, animationName) {
  20021. var animatable = this.getAnimatableByTarget(target);
  20022. if (animatable) {
  20023. animatable.stop(animationName);
  20024. }
  20025. };
  20026. /**
  20027. * Stops and removes all animations that have been applied to the scene
  20028. */
  20029. Scene.prototype.stopAllAnimations = function () {
  20030. if (this._activeAnimatables) {
  20031. for (var i = 0; i < this._activeAnimatables.length; i++) {
  20032. this._activeAnimatables[i].stop();
  20033. }
  20034. this._activeAnimatables = [];
  20035. }
  20036. };
  20037. Scene.prototype._animate = function () {
  20038. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  20039. return;
  20040. }
  20041. // Getting time
  20042. var now = BABYLON.Tools.Now;
  20043. if (!this._animationTimeLast) {
  20044. if (this._pendingData.length > 0) {
  20045. return;
  20046. }
  20047. this._animationTimeLast = now;
  20048. }
  20049. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  20050. this._animationTime += deltaTime;
  20051. this._animationTimeLast = now;
  20052. for (var index = 0; index < this._activeAnimatables.length; index++) {
  20053. this._activeAnimatables[index]._animate(this._animationTime);
  20054. }
  20055. };
  20056. // Matrix
  20057. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  20058. this._useAlternateCameraConfiguration = active;
  20059. };
  20060. Scene.prototype.getViewMatrix = function () {
  20061. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  20062. };
  20063. Scene.prototype.getProjectionMatrix = function () {
  20064. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  20065. };
  20066. Scene.prototype.getTransformMatrix = function () {
  20067. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  20068. };
  20069. Scene.prototype.setTransformMatrix = function (view, projection) {
  20070. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  20071. return;
  20072. }
  20073. this._viewUpdateFlag = view.updateFlag;
  20074. this._projectionUpdateFlag = projection.updateFlag;
  20075. this._viewMatrix = view;
  20076. this._projectionMatrix = projection;
  20077. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20078. // Update frustum
  20079. if (!this._frustumPlanes) {
  20080. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20081. }
  20082. else {
  20083. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20084. }
  20085. if (this.activeCamera && this.activeCamera._alternateCamera) {
  20086. var otherCamera = this.activeCamera._alternateCamera;
  20087. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  20088. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  20089. }
  20090. if (this._sceneUbo.useUbo) {
  20091. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  20092. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  20093. this._sceneUbo.update();
  20094. }
  20095. };
  20096. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  20097. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  20098. return;
  20099. }
  20100. this._alternateViewUpdateFlag = view.updateFlag;
  20101. this._alternateProjectionUpdateFlag = projection.updateFlag;
  20102. this._alternateViewMatrix = view;
  20103. this._alternateProjectionMatrix = projection;
  20104. if (!this._alternateTransformMatrix) {
  20105. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  20106. }
  20107. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  20108. if (!this._alternateSceneUbo) {
  20109. this._createAlternateUbo();
  20110. }
  20111. if (this._alternateSceneUbo.useUbo) {
  20112. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  20113. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  20114. this._alternateSceneUbo.update();
  20115. }
  20116. };
  20117. Scene.prototype.getSceneUniformBuffer = function () {
  20118. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  20119. };
  20120. // Methods
  20121. Scene.prototype.getUniqueId = function () {
  20122. var result = Scene._uniqueIdCounter;
  20123. Scene._uniqueIdCounter++;
  20124. return result;
  20125. };
  20126. Scene.prototype.addMesh = function (newMesh) {
  20127. this.meshes.push(newMesh);
  20128. //notify the collision coordinator
  20129. if (this.collisionCoordinator) {
  20130. this.collisionCoordinator.onMeshAdded(newMesh);
  20131. }
  20132. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  20133. };
  20134. Scene.prototype.removeMesh = function (toRemove) {
  20135. var index = this.meshes.indexOf(toRemove);
  20136. if (index !== -1) {
  20137. // Remove from the scene if mesh found
  20138. this.meshes.splice(index, 1);
  20139. }
  20140. this.onMeshRemovedObservable.notifyObservers(toRemove);
  20141. return index;
  20142. };
  20143. Scene.prototype.addTransformNode = function (newTransformNode) {
  20144. this.transformNodes.push(newTransformNode);
  20145. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  20146. };
  20147. Scene.prototype.removeTransformNode = function (toRemove) {
  20148. var index = this.transformNodes.indexOf(toRemove);
  20149. if (index !== -1) {
  20150. // Remove from the scene if found
  20151. this.transformNodes.splice(index, 1);
  20152. }
  20153. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  20154. return index;
  20155. };
  20156. Scene.prototype.removeSkeleton = function (toRemove) {
  20157. var index = this.skeletons.indexOf(toRemove);
  20158. if (index !== -1) {
  20159. // Remove from the scene if found
  20160. this.skeletons.splice(index, 1);
  20161. }
  20162. return index;
  20163. };
  20164. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  20165. var index = this.morphTargetManagers.indexOf(toRemove);
  20166. if (index !== -1) {
  20167. // Remove from the scene if found
  20168. this.morphTargetManagers.splice(index, 1);
  20169. }
  20170. return index;
  20171. };
  20172. Scene.prototype.removeLight = function (toRemove) {
  20173. var index = this.lights.indexOf(toRemove);
  20174. if (index !== -1) {
  20175. // Remove from meshes
  20176. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  20177. var mesh = _a[_i];
  20178. mesh._removeLightSource(toRemove);
  20179. }
  20180. // Remove from the scene if mesh found
  20181. this.lights.splice(index, 1);
  20182. this.sortLightsByPriority();
  20183. }
  20184. this.onLightRemovedObservable.notifyObservers(toRemove);
  20185. return index;
  20186. };
  20187. Scene.prototype.removeCamera = function (toRemove) {
  20188. var index = this.cameras.indexOf(toRemove);
  20189. if (index !== -1) {
  20190. // Remove from the scene if mesh found
  20191. this.cameras.splice(index, 1);
  20192. }
  20193. // Remove from activeCameras
  20194. var index2 = this.activeCameras.indexOf(toRemove);
  20195. if (index2 !== -1) {
  20196. // Remove from the scene if mesh found
  20197. this.activeCameras.splice(index2, 1);
  20198. }
  20199. // Reset the activeCamera
  20200. if (this.activeCamera === toRemove) {
  20201. if (this.cameras.length > 0) {
  20202. this.activeCamera = this.cameras[0];
  20203. }
  20204. else {
  20205. this.activeCamera = null;
  20206. }
  20207. }
  20208. this.onCameraRemovedObservable.notifyObservers(toRemove);
  20209. return index;
  20210. };
  20211. Scene.prototype.addLight = function (newLight) {
  20212. this.lights.push(newLight);
  20213. this.sortLightsByPriority();
  20214. // Add light to all meshes (To support if the light is removed and then readded)
  20215. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  20216. var mesh = _a[_i];
  20217. if (mesh._lightSources.indexOf(newLight) === -1) {
  20218. mesh._lightSources.push(newLight);
  20219. mesh._resyncLightSources();
  20220. }
  20221. }
  20222. this.onNewLightAddedObservable.notifyObservers(newLight);
  20223. };
  20224. Scene.prototype.sortLightsByPriority = function () {
  20225. if (this.requireLightSorting) {
  20226. this.lights.sort(BABYLON.Light.compareLightsPriority);
  20227. }
  20228. };
  20229. Scene.prototype.addCamera = function (newCamera) {
  20230. this.cameras.push(newCamera);
  20231. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  20232. };
  20233. /**
  20234. * Switch active camera
  20235. * @param {Camera} newCamera - new active camera
  20236. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  20237. */
  20238. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  20239. if (attachControl === void 0) { attachControl = true; }
  20240. var canvas = this._engine.getRenderingCanvas();
  20241. if (!canvas) {
  20242. return;
  20243. }
  20244. if (this.activeCamera) {
  20245. this.activeCamera.detachControl(canvas);
  20246. }
  20247. this.activeCamera = newCamera;
  20248. if (attachControl) {
  20249. newCamera.attachControl(canvas);
  20250. }
  20251. };
  20252. /**
  20253. * sets the active camera of the scene using its ID
  20254. * @param {string} id - the camera's ID
  20255. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  20256. * @see activeCamera
  20257. */
  20258. Scene.prototype.setActiveCameraByID = function (id) {
  20259. var camera = this.getCameraByID(id);
  20260. if (camera) {
  20261. this.activeCamera = camera;
  20262. return camera;
  20263. }
  20264. return null;
  20265. };
  20266. /**
  20267. * sets the active camera of the scene using its name
  20268. * @param {string} name - the camera's name
  20269. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  20270. * @see activeCamera
  20271. */
  20272. Scene.prototype.setActiveCameraByName = function (name) {
  20273. var camera = this.getCameraByName(name);
  20274. if (camera) {
  20275. this.activeCamera = camera;
  20276. return camera;
  20277. }
  20278. return null;
  20279. };
  20280. /**
  20281. * get an animation group using its name
  20282. * @param {string} the material's name
  20283. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  20284. */
  20285. Scene.prototype.getAnimationGroupByName = function (name) {
  20286. for (var index = 0; index < this.animationGroups.length; index++) {
  20287. if (this.animationGroups[index].name === name) {
  20288. return this.animationGroups[index];
  20289. }
  20290. }
  20291. return null;
  20292. };
  20293. /**
  20294. * get a material using its id
  20295. * @param {string} the material's ID
  20296. * @return {BABYLON.Material|null} the material or null if none found.
  20297. */
  20298. Scene.prototype.getMaterialByID = function (id) {
  20299. for (var index = 0; index < this.materials.length; index++) {
  20300. if (this.materials[index].id === id) {
  20301. return this.materials[index];
  20302. }
  20303. }
  20304. return null;
  20305. };
  20306. /**
  20307. * get a material using its name
  20308. * @param {string} the material's name
  20309. * @return {BABYLON.Material|null} the material or null if none found.
  20310. */
  20311. Scene.prototype.getMaterialByName = function (name) {
  20312. for (var index = 0; index < this.materials.length; index++) {
  20313. if (this.materials[index].name === name) {
  20314. return this.materials[index];
  20315. }
  20316. }
  20317. return null;
  20318. };
  20319. Scene.prototype.getLensFlareSystemByName = function (name) {
  20320. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  20321. if (this.lensFlareSystems[index].name === name) {
  20322. return this.lensFlareSystems[index];
  20323. }
  20324. }
  20325. return null;
  20326. };
  20327. Scene.prototype.getLensFlareSystemByID = function (id) {
  20328. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  20329. if (this.lensFlareSystems[index].id === id) {
  20330. return this.lensFlareSystems[index];
  20331. }
  20332. }
  20333. return null;
  20334. };
  20335. Scene.prototype.getCameraByID = function (id) {
  20336. for (var index = 0; index < this.cameras.length; index++) {
  20337. if (this.cameras[index].id === id) {
  20338. return this.cameras[index];
  20339. }
  20340. }
  20341. return null;
  20342. };
  20343. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  20344. for (var index = 0; index < this.cameras.length; index++) {
  20345. if (this.cameras[index].uniqueId === uniqueId) {
  20346. return this.cameras[index];
  20347. }
  20348. }
  20349. return null;
  20350. };
  20351. /**
  20352. * get a camera using its name
  20353. * @param {string} the camera's name
  20354. * @return {BABYLON.Camera|null} the camera or null if none found.
  20355. */
  20356. Scene.prototype.getCameraByName = function (name) {
  20357. for (var index = 0; index < this.cameras.length; index++) {
  20358. if (this.cameras[index].name === name) {
  20359. return this.cameras[index];
  20360. }
  20361. }
  20362. return null;
  20363. };
  20364. /**
  20365. * get a bone using its id
  20366. * @param {string} the bone's id
  20367. * @return {BABYLON.Bone|null} the bone or null if not found
  20368. */
  20369. Scene.prototype.getBoneByID = function (id) {
  20370. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  20371. var skeleton = this.skeletons[skeletonIndex];
  20372. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  20373. if (skeleton.bones[boneIndex].id === id) {
  20374. return skeleton.bones[boneIndex];
  20375. }
  20376. }
  20377. }
  20378. return null;
  20379. };
  20380. /**
  20381. * get a bone using its id
  20382. * @param {string} the bone's name
  20383. * @return {BABYLON.Bone|null} the bone or null if not found
  20384. */
  20385. Scene.prototype.getBoneByName = function (name) {
  20386. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  20387. var skeleton = this.skeletons[skeletonIndex];
  20388. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  20389. if (skeleton.bones[boneIndex].name === name) {
  20390. return skeleton.bones[boneIndex];
  20391. }
  20392. }
  20393. }
  20394. return null;
  20395. };
  20396. /**
  20397. * get a light node using its name
  20398. * @param {string} the light's name
  20399. * @return {BABYLON.Light|null} the light or null if none found.
  20400. */
  20401. Scene.prototype.getLightByName = function (name) {
  20402. for (var index = 0; index < this.lights.length; index++) {
  20403. if (this.lights[index].name === name) {
  20404. return this.lights[index];
  20405. }
  20406. }
  20407. return null;
  20408. };
  20409. /**
  20410. * get a light node using its ID
  20411. * @param {string} the light's id
  20412. * @return {BABYLON.Light|null} the light or null if none found.
  20413. */
  20414. Scene.prototype.getLightByID = function (id) {
  20415. for (var index = 0; index < this.lights.length; index++) {
  20416. if (this.lights[index].id === id) {
  20417. return this.lights[index];
  20418. }
  20419. }
  20420. return null;
  20421. };
  20422. /**
  20423. * get a light node using its scene-generated unique ID
  20424. * @param {number} the light's unique id
  20425. * @return {BABYLON.Light|null} the light or null if none found.
  20426. */
  20427. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  20428. for (var index = 0; index < this.lights.length; index++) {
  20429. if (this.lights[index].uniqueId === uniqueId) {
  20430. return this.lights[index];
  20431. }
  20432. }
  20433. return null;
  20434. };
  20435. /**
  20436. * get a particle system by id
  20437. * @param id {number} the particle system id
  20438. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  20439. */
  20440. Scene.prototype.getParticleSystemByID = function (id) {
  20441. for (var index = 0; index < this.particleSystems.length; index++) {
  20442. if (this.particleSystems[index].id === id) {
  20443. return this.particleSystems[index];
  20444. }
  20445. }
  20446. return null;
  20447. };
  20448. /**
  20449. * get a geometry using its ID
  20450. * @param {string} the geometry's id
  20451. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  20452. */
  20453. Scene.prototype.getGeometryByID = function (id) {
  20454. for (var index = 0; index < this._geometries.length; index++) {
  20455. if (this._geometries[index].id === id) {
  20456. return this._geometries[index];
  20457. }
  20458. }
  20459. return null;
  20460. };
  20461. /**
  20462. * add a new geometry to this scene.
  20463. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  20464. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  20465. * @return {boolean} was the geometry added or not
  20466. */
  20467. Scene.prototype.pushGeometry = function (geometry, force) {
  20468. if (!force && this.getGeometryByID(geometry.id)) {
  20469. return false;
  20470. }
  20471. this._geometries.push(geometry);
  20472. //notify the collision coordinator
  20473. if (this.collisionCoordinator) {
  20474. this.collisionCoordinator.onGeometryAdded(geometry);
  20475. }
  20476. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  20477. return true;
  20478. };
  20479. /**
  20480. * Removes an existing geometry
  20481. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  20482. * @return {boolean} was the geometry removed or not
  20483. */
  20484. Scene.prototype.removeGeometry = function (geometry) {
  20485. var index = this._geometries.indexOf(geometry);
  20486. if (index > -1) {
  20487. this._geometries.splice(index, 1);
  20488. //notify the collision coordinator
  20489. if (this.collisionCoordinator) {
  20490. this.collisionCoordinator.onGeometryDeleted(geometry);
  20491. }
  20492. this.onGeometryRemovedObservable.notifyObservers(geometry);
  20493. return true;
  20494. }
  20495. return false;
  20496. };
  20497. Scene.prototype.getGeometries = function () {
  20498. return this._geometries;
  20499. };
  20500. /**
  20501. * Get the first added mesh found of a given ID
  20502. * @param {string} id - the id to search for
  20503. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  20504. */
  20505. Scene.prototype.getMeshByID = function (id) {
  20506. for (var index = 0; index < this.meshes.length; index++) {
  20507. if (this.meshes[index].id === id) {
  20508. return this.meshes[index];
  20509. }
  20510. }
  20511. return null;
  20512. };
  20513. Scene.prototype.getMeshesByID = function (id) {
  20514. return this.meshes.filter(function (m) {
  20515. return m.id === id;
  20516. });
  20517. };
  20518. /**
  20519. * Get the first added transform node found of a given ID
  20520. * @param {string} id - the id to search for
  20521. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  20522. */
  20523. Scene.prototype.getTransformNodeByID = function (id) {
  20524. for (var index = 0; index < this.transformNodes.length; index++) {
  20525. if (this.transformNodes[index].id === id) {
  20526. return this.transformNodes[index];
  20527. }
  20528. }
  20529. return null;
  20530. };
  20531. Scene.prototype.getTransformNodesByID = function (id) {
  20532. return this.transformNodes.filter(function (m) {
  20533. return m.id === id;
  20534. });
  20535. };
  20536. /**
  20537. * Get a mesh with its auto-generated unique id
  20538. * @param {number} uniqueId - the unique id to search for
  20539. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  20540. */
  20541. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  20542. for (var index = 0; index < this.meshes.length; index++) {
  20543. if (this.meshes[index].uniqueId === uniqueId) {
  20544. return this.meshes[index];
  20545. }
  20546. }
  20547. return null;
  20548. };
  20549. /**
  20550. * Get a the last added mesh found of a given ID
  20551. * @param {string} id - the id to search for
  20552. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  20553. */
  20554. Scene.prototype.getLastMeshByID = function (id) {
  20555. for (var index = this.meshes.length - 1; index >= 0; index--) {
  20556. if (this.meshes[index].id === id) {
  20557. return this.meshes[index];
  20558. }
  20559. }
  20560. return null;
  20561. };
  20562. /**
  20563. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  20564. * @param {string} id - the id to search for
  20565. * @return {BABYLON.Node|null} the node found or null if not found at all.
  20566. */
  20567. Scene.prototype.getLastEntryByID = function (id) {
  20568. var index;
  20569. for (index = this.meshes.length - 1; index >= 0; index--) {
  20570. if (this.meshes[index].id === id) {
  20571. return this.meshes[index];
  20572. }
  20573. }
  20574. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  20575. if (this.transformNodes[index].id === id) {
  20576. return this.transformNodes[index];
  20577. }
  20578. }
  20579. for (index = this.cameras.length - 1; index >= 0; index--) {
  20580. if (this.cameras[index].id === id) {
  20581. return this.cameras[index];
  20582. }
  20583. }
  20584. for (index = this.lights.length - 1; index >= 0; index--) {
  20585. if (this.lights[index].id === id) {
  20586. return this.lights[index];
  20587. }
  20588. }
  20589. return null;
  20590. };
  20591. Scene.prototype.getNodeByID = function (id) {
  20592. var mesh = this.getMeshByID(id);
  20593. if (mesh) {
  20594. return mesh;
  20595. }
  20596. var light = this.getLightByID(id);
  20597. if (light) {
  20598. return light;
  20599. }
  20600. var camera = this.getCameraByID(id);
  20601. if (camera) {
  20602. return camera;
  20603. }
  20604. var bone = this.getBoneByID(id);
  20605. return bone;
  20606. };
  20607. Scene.prototype.getNodeByName = function (name) {
  20608. var mesh = this.getMeshByName(name);
  20609. if (mesh) {
  20610. return mesh;
  20611. }
  20612. var light = this.getLightByName(name);
  20613. if (light) {
  20614. return light;
  20615. }
  20616. var camera = this.getCameraByName(name);
  20617. if (camera) {
  20618. return camera;
  20619. }
  20620. var bone = this.getBoneByName(name);
  20621. return bone;
  20622. };
  20623. Scene.prototype.getMeshByName = function (name) {
  20624. for (var index = 0; index < this.meshes.length; index++) {
  20625. if (this.meshes[index].name === name) {
  20626. return this.meshes[index];
  20627. }
  20628. }
  20629. return null;
  20630. };
  20631. Scene.prototype.getTransformNodeByName = function (name) {
  20632. for (var index = 0; index < this.transformNodes.length; index++) {
  20633. if (this.transformNodes[index].name === name) {
  20634. return this.transformNodes[index];
  20635. }
  20636. }
  20637. return null;
  20638. };
  20639. Scene.prototype.getSoundByName = function (name) {
  20640. var index;
  20641. if (BABYLON.AudioEngine) {
  20642. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  20643. if (this.mainSoundTrack.soundCollection[index].name === name) {
  20644. return this.mainSoundTrack.soundCollection[index];
  20645. }
  20646. }
  20647. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  20648. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  20649. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  20650. return this.soundTracks[sdIndex].soundCollection[index];
  20651. }
  20652. }
  20653. }
  20654. }
  20655. return null;
  20656. };
  20657. Scene.prototype.getLastSkeletonByID = function (id) {
  20658. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  20659. if (this.skeletons[index].id === id) {
  20660. return this.skeletons[index];
  20661. }
  20662. }
  20663. return null;
  20664. };
  20665. Scene.prototype.getSkeletonById = function (id) {
  20666. for (var index = 0; index < this.skeletons.length; index++) {
  20667. if (this.skeletons[index].id === id) {
  20668. return this.skeletons[index];
  20669. }
  20670. }
  20671. return null;
  20672. };
  20673. Scene.prototype.getSkeletonByName = function (name) {
  20674. for (var index = 0; index < this.skeletons.length; index++) {
  20675. if (this.skeletons[index].name === name) {
  20676. return this.skeletons[index];
  20677. }
  20678. }
  20679. return null;
  20680. };
  20681. Scene.prototype.getMorphTargetManagerById = function (id) {
  20682. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  20683. if (this.morphTargetManagers[index].uniqueId === id) {
  20684. return this.morphTargetManagers[index];
  20685. }
  20686. }
  20687. return null;
  20688. };
  20689. Scene.prototype.isActiveMesh = function (mesh) {
  20690. return (this._activeMeshes.indexOf(mesh) !== -1);
  20691. };
  20692. /**
  20693. * Return a the first highlight layer of the scene with a given name.
  20694. * @param name The name of the highlight layer to look for.
  20695. * @return The highlight layer if found otherwise null.
  20696. */
  20697. Scene.prototype.getHighlightLayerByName = function (name) {
  20698. for (var index = 0; index < this.highlightLayers.length; index++) {
  20699. if (this.highlightLayers[index].name === name) {
  20700. return this.highlightLayers[index];
  20701. }
  20702. }
  20703. return null;
  20704. };
  20705. Object.defineProperty(Scene.prototype, "uid", {
  20706. /**
  20707. * Return a unique id as a string which can serve as an identifier for the scene
  20708. */
  20709. get: function () {
  20710. if (!this._uid) {
  20711. this._uid = BABYLON.Tools.RandomId();
  20712. }
  20713. return this._uid;
  20714. },
  20715. enumerable: true,
  20716. configurable: true
  20717. });
  20718. /**
  20719. * Add an externaly attached data from its key.
  20720. * This method call will fail and return false, if such key already exists.
  20721. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  20722. * @param key the unique key that identifies the data
  20723. * @param data the data object to associate to the key for this Engine instance
  20724. * @return true if no such key were already present and the data was added successfully, false otherwise
  20725. */
  20726. Scene.prototype.addExternalData = function (key, data) {
  20727. if (!this._externalData) {
  20728. this._externalData = new BABYLON.StringDictionary();
  20729. }
  20730. return this._externalData.add(key, data);
  20731. };
  20732. /**
  20733. * Get an externaly attached data from its key
  20734. * @param key the unique key that identifies the data
  20735. * @return the associated data, if present (can be null), or undefined if not present
  20736. */
  20737. Scene.prototype.getExternalData = function (key) {
  20738. if (!this._externalData) {
  20739. return null;
  20740. }
  20741. return this._externalData.get(key);
  20742. };
  20743. /**
  20744. * Get an externaly attached data from its key, create it using a factory if it's not already present
  20745. * @param key the unique key that identifies the data
  20746. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  20747. * @return the associated data, can be null if the factory returned null.
  20748. */
  20749. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  20750. if (!this._externalData) {
  20751. this._externalData = new BABYLON.StringDictionary();
  20752. }
  20753. return this._externalData.getOrAddWithFactory(key, factory);
  20754. };
  20755. /**
  20756. * Remove an externaly attached data from the Engine instance
  20757. * @param key the unique key that identifies the data
  20758. * @return true if the data was successfully removed, false if it doesn't exist
  20759. */
  20760. Scene.prototype.removeExternalData = function (key) {
  20761. return this._externalData.remove(key);
  20762. };
  20763. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  20764. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  20765. if (mesh.showSubMeshesBoundingBox) {
  20766. var boundingInfo = subMesh.getBoundingInfo();
  20767. if (boundingInfo !== null && boundingInfo !== undefined) {
  20768. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  20769. }
  20770. }
  20771. var material = subMesh.getMaterial();
  20772. if (material !== null && material !== undefined) {
  20773. // Render targets
  20774. if (material.getRenderTargetTextures !== undefined) {
  20775. if (this._processedMaterials.indexOf(material) === -1) {
  20776. this._processedMaterials.push(material);
  20777. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  20778. }
  20779. }
  20780. // Dispatch
  20781. this._activeIndices.addCount(subMesh.indexCount, false);
  20782. this._renderingManager.dispatch(subMesh, mesh, material);
  20783. }
  20784. }
  20785. };
  20786. Scene.prototype._isInIntermediateRendering = function () {
  20787. return this._intermediateRendering;
  20788. };
  20789. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  20790. this._activeMeshCandidateProvider = provider;
  20791. };
  20792. Scene.prototype.getActiveMeshCandidateProvider = function () {
  20793. return this._activeMeshCandidateProvider;
  20794. };
  20795. /**
  20796. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  20797. */
  20798. Scene.prototype.freezeActiveMeshes = function () {
  20799. this._evaluateActiveMeshes();
  20800. this._activeMeshesFrozen = true;
  20801. return this;
  20802. };
  20803. /**
  20804. * Use this function to restart evaluating active meshes on every frame
  20805. */
  20806. Scene.prototype.unfreezeActiveMeshes = function () {
  20807. this._activeMeshesFrozen = false;
  20808. return this;
  20809. };
  20810. Scene.prototype._evaluateActiveMeshes = function () {
  20811. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  20812. return;
  20813. }
  20814. if (!this.activeCamera) {
  20815. return;
  20816. }
  20817. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  20818. this.activeCamera._activeMeshes.reset();
  20819. this._activeMeshes.reset();
  20820. this._renderingManager.reset();
  20821. this._processedMaterials.reset();
  20822. this._activeParticleSystems.reset();
  20823. this._activeSkeletons.reset();
  20824. this._softwareSkinnedMeshes.reset();
  20825. if (this._boundingBoxRenderer) {
  20826. this._boundingBoxRenderer.reset();
  20827. }
  20828. // Meshes
  20829. var meshes;
  20830. var len;
  20831. var checkIsEnabled = true;
  20832. // Determine mesh candidates
  20833. if (this._activeMeshCandidateProvider !== undefined) {
  20834. // Use _activeMeshCandidateProvider
  20835. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  20836. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  20837. if (meshes !== undefined) {
  20838. len = meshes.length;
  20839. }
  20840. else {
  20841. len = 0;
  20842. }
  20843. }
  20844. else if (this._selectionOctree !== undefined) {
  20845. // Octree
  20846. var selection = this._selectionOctree.select(this._frustumPlanes);
  20847. meshes = selection.data;
  20848. len = selection.length;
  20849. }
  20850. else {
  20851. // Full scene traversal
  20852. len = this.meshes.length;
  20853. meshes = this.meshes;
  20854. }
  20855. // Check each mesh
  20856. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  20857. mesh = meshes[meshIndex];
  20858. if (mesh.isBlocked) {
  20859. continue;
  20860. }
  20861. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  20862. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  20863. continue;
  20864. }
  20865. mesh.computeWorldMatrix();
  20866. // Intersections
  20867. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  20868. this._meshesForIntersections.pushNoDuplicate(mesh);
  20869. }
  20870. // Switch to current LOD
  20871. meshLOD = mesh.getLOD(this.activeCamera);
  20872. if (meshLOD === undefined || meshLOD === null) {
  20873. continue;
  20874. }
  20875. mesh._preActivate();
  20876. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  20877. this._activeMeshes.push(mesh);
  20878. this.activeCamera._activeMeshes.push(mesh);
  20879. mesh._activate(this._renderId);
  20880. if (meshLOD !== mesh) {
  20881. meshLOD._activate(this._renderId);
  20882. }
  20883. this._activeMesh(mesh, meshLOD);
  20884. }
  20885. }
  20886. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  20887. // Particle systems
  20888. if (this.particlesEnabled) {
  20889. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  20890. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  20891. var particleSystem = this.particleSystems[particleIndex];
  20892. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  20893. continue;
  20894. }
  20895. var emitter = particleSystem.emitter;
  20896. if (!emitter.position || emitter.isEnabled()) {
  20897. this._activeParticleSystems.push(particleSystem);
  20898. particleSystem.animate();
  20899. this._renderingManager.dispatchParticles(particleSystem);
  20900. }
  20901. }
  20902. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  20903. }
  20904. };
  20905. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  20906. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  20907. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  20908. mesh.skeleton.prepare();
  20909. }
  20910. if (!mesh.computeBonesUsingShaders) {
  20911. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  20912. }
  20913. }
  20914. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  20915. var boundingInfo = sourceMesh.getBoundingInfo();
  20916. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  20917. }
  20918. if (mesh !== undefined && mesh !== null
  20919. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  20920. // Submeshes Octrees
  20921. var len;
  20922. var subMeshes;
  20923. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  20924. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  20925. len = intersections.length;
  20926. subMeshes = intersections.data;
  20927. }
  20928. else {
  20929. subMeshes = mesh.subMeshes;
  20930. len = subMeshes.length;
  20931. }
  20932. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  20933. subMesh = subMeshes[subIndex];
  20934. this._evaluateSubMesh(subMesh, mesh);
  20935. }
  20936. }
  20937. };
  20938. Scene.prototype.updateTransformMatrix = function (force) {
  20939. if (!this.activeCamera) {
  20940. return;
  20941. }
  20942. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  20943. };
  20944. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  20945. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  20946. };
  20947. Scene.prototype._renderForCamera = function (camera) {
  20948. if (camera && camera._skipRendering) {
  20949. return;
  20950. }
  20951. var engine = this._engine;
  20952. this.activeCamera = camera;
  20953. if (!this.activeCamera)
  20954. throw new Error("Active camera not set");
  20955. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  20956. // Viewport
  20957. engine.setViewport(this.activeCamera.viewport);
  20958. // Camera
  20959. this.resetCachedMaterial();
  20960. this._renderId++;
  20961. this.activeCamera.update();
  20962. this.updateTransformMatrix();
  20963. if (camera._alternateCamera) {
  20964. this.updateAlternateTransformMatrix(camera._alternateCamera);
  20965. this._alternateRendering = true;
  20966. }
  20967. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  20968. // Meshes
  20969. this._evaluateActiveMeshes();
  20970. // Software skinning
  20971. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  20972. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  20973. mesh.applySkeleton(mesh.skeleton);
  20974. }
  20975. // Render targets
  20976. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  20977. var needsRestoreFrameBuffer = false;
  20978. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  20979. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  20980. }
  20981. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  20982. this._intermediateRendering = true;
  20983. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  20984. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  20985. var renderTarget = this._renderTargets.data[renderIndex];
  20986. if (renderTarget._shouldRender()) {
  20987. this._renderId++;
  20988. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  20989. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  20990. }
  20991. }
  20992. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  20993. this._intermediateRendering = false;
  20994. this._renderId++;
  20995. needsRestoreFrameBuffer = true; // Restore back buffer
  20996. }
  20997. // Render HighlightLayer Texture
  20998. var stencilState = this._engine.getStencilBuffer();
  20999. var renderhighlights = false;
  21000. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  21001. this._intermediateRendering = true;
  21002. for (var i = 0; i < this.highlightLayers.length; i++) {
  21003. var highlightLayer = this.highlightLayers[i];
  21004. if (highlightLayer.shouldRender() &&
  21005. (!highlightLayer.camera ||
  21006. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  21007. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  21008. renderhighlights = true;
  21009. var renderTarget = highlightLayer._mainTexture;
  21010. if (renderTarget._shouldRender()) {
  21011. this._renderId++;
  21012. renderTarget.render(false, false);
  21013. needsRestoreFrameBuffer = true;
  21014. }
  21015. }
  21016. }
  21017. this._intermediateRendering = false;
  21018. this._renderId++;
  21019. }
  21020. if (needsRestoreFrameBuffer) {
  21021. engine.restoreDefaultFramebuffer(); // Restore back buffer
  21022. }
  21023. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  21024. // Prepare Frame
  21025. this.postProcessManager._prepareFrame();
  21026. // Backgrounds
  21027. var layerIndex;
  21028. var layer;
  21029. if (this.layers.length) {
  21030. engine.setDepthBuffer(false);
  21031. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  21032. layer = this.layers[layerIndex];
  21033. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  21034. layer.render();
  21035. }
  21036. }
  21037. engine.setDepthBuffer(true);
  21038. }
  21039. // Activate HighlightLayer stencil
  21040. if (renderhighlights) {
  21041. this._engine.setStencilBuffer(true);
  21042. }
  21043. // Render
  21044. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  21045. this._renderingManager.render(null, null, true, true);
  21046. this.onAfterDrawPhaseObservable.notifyObservers(this);
  21047. // Restore HighlightLayer stencil
  21048. if (renderhighlights) {
  21049. this._engine.setStencilBuffer(stencilState);
  21050. }
  21051. // Bounding boxes
  21052. if (this._boundingBoxRenderer) {
  21053. this._boundingBoxRenderer.render();
  21054. }
  21055. // Lens flares
  21056. if (this.lensFlaresEnabled) {
  21057. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  21058. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  21059. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  21060. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  21061. lensFlareSystem.render();
  21062. }
  21063. }
  21064. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  21065. }
  21066. // Foregrounds
  21067. if (this.layers.length) {
  21068. engine.setDepthBuffer(false);
  21069. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  21070. layer = this.layers[layerIndex];
  21071. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  21072. layer.render();
  21073. }
  21074. }
  21075. engine.setDepthBuffer(true);
  21076. }
  21077. // Highlight Layer
  21078. if (renderhighlights) {
  21079. engine.setDepthBuffer(false);
  21080. for (var i = 0; i < this.highlightLayers.length; i++) {
  21081. if (this.highlightLayers[i].shouldRender()) {
  21082. this.highlightLayers[i].render();
  21083. }
  21084. }
  21085. engine.setDepthBuffer(true);
  21086. }
  21087. // Finalize frame
  21088. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  21089. // Reset some special arrays
  21090. this._renderTargets.reset();
  21091. this._alternateRendering = false;
  21092. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  21093. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  21094. };
  21095. Scene.prototype._processSubCameras = function (camera) {
  21096. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  21097. this._renderForCamera(camera);
  21098. return;
  21099. }
  21100. // Update camera
  21101. if (this.activeCamera) {
  21102. this.activeCamera.update();
  21103. }
  21104. // rig cameras
  21105. for (var index = 0; index < camera._rigCameras.length; index++) {
  21106. this._renderForCamera(camera._rigCameras[index]);
  21107. }
  21108. this.activeCamera = camera;
  21109. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  21110. };
  21111. Scene.prototype._checkIntersections = function () {
  21112. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  21113. var sourceMesh = this._meshesForIntersections.data[index];
  21114. if (!sourceMesh.actionManager) {
  21115. continue;
  21116. }
  21117. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  21118. var action = sourceMesh.actionManager.actions[actionIndex];
  21119. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  21120. var parameters = action.getTriggerParameter();
  21121. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  21122. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  21123. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  21124. if (areIntersecting && currentIntersectionInProgress === -1) {
  21125. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  21126. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  21127. sourceMesh._intersectionsInProgress.push(otherMesh);
  21128. }
  21129. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  21130. sourceMesh._intersectionsInProgress.push(otherMesh);
  21131. }
  21132. }
  21133. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  21134. //They intersected, and now they don't.
  21135. //is this trigger an exit trigger? execute an event.
  21136. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  21137. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  21138. }
  21139. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  21140. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  21141. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  21142. }
  21143. }
  21144. }
  21145. }
  21146. }
  21147. };
  21148. Scene.prototype.render = function () {
  21149. if (this.isDisposed) {
  21150. return;
  21151. }
  21152. this._activeParticles.fetchNewFrame();
  21153. this._totalVertices.fetchNewFrame();
  21154. this._activeIndices.fetchNewFrame();
  21155. this._activeBones.fetchNewFrame();
  21156. this._meshesForIntersections.reset();
  21157. this.resetCachedMaterial();
  21158. this.onBeforeAnimationsObservable.notifyObservers(this);
  21159. // Actions
  21160. if (this.actionManager) {
  21161. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  21162. }
  21163. //Simplification Queue
  21164. if (this.simplificationQueue && !this.simplificationQueue.running) {
  21165. this.simplificationQueue.executeNext();
  21166. }
  21167. if (this._engine.isDeterministicLockStep()) {
  21168. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  21169. var defaultFPS = (60.0 / 1000.0);
  21170. var defaultFrameTime = 1000 / 60; // frame time in MS
  21171. if (this._physicsEngine) {
  21172. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  21173. }
  21174. var stepsTaken = 0;
  21175. var maxSubSteps = this._engine.getLockstepMaxSteps();
  21176. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  21177. internalSteps = Math.min(internalSteps, maxSubSteps);
  21178. do {
  21179. this.onBeforeStepObservable.notifyObservers(this);
  21180. // Animations
  21181. this._animationRatio = defaultFrameTime * defaultFPS;
  21182. this._animate();
  21183. this.onAfterAnimationsObservable.notifyObservers(this);
  21184. // Physics
  21185. if (this._physicsEngine) {
  21186. this.onBeforePhysicsObservable.notifyObservers(this);
  21187. this._physicsEngine._step(defaultFrameTime / 1000);
  21188. this.onAfterPhysicsObservable.notifyObservers(this);
  21189. }
  21190. this.onAfterStepObservable.notifyObservers(this);
  21191. this._currentStepId++;
  21192. stepsTaken++;
  21193. deltaTime -= defaultFrameTime;
  21194. } while (deltaTime > 0 && stepsTaken < internalSteps);
  21195. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  21196. }
  21197. else {
  21198. // Animations
  21199. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  21200. this._animationRatio = deltaTime * (60.0 / 1000.0);
  21201. this._animate();
  21202. this.onAfterAnimationsObservable.notifyObservers(this);
  21203. // Physics
  21204. if (this._physicsEngine) {
  21205. this.onBeforePhysicsObservable.notifyObservers(this);
  21206. this._physicsEngine._step(deltaTime / 1000.0);
  21207. this.onAfterPhysicsObservable.notifyObservers(this);
  21208. }
  21209. }
  21210. // update gamepad manager
  21211. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  21212. this._gamepadManager._checkGamepadsStatus();
  21213. }
  21214. // Before render
  21215. this.onBeforeRenderObservable.notifyObservers(this);
  21216. // Customs render targets
  21217. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  21218. var engine = this.getEngine();
  21219. var currentActiveCamera = this.activeCamera;
  21220. if (this.renderTargetsEnabled) {
  21221. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  21222. this._intermediateRendering = true;
  21223. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  21224. var renderTarget = this.customRenderTargets[customIndex];
  21225. if (renderTarget._shouldRender()) {
  21226. this._renderId++;
  21227. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  21228. if (!this.activeCamera)
  21229. throw new Error("Active camera not set");
  21230. // Viewport
  21231. engine.setViewport(this.activeCamera.viewport);
  21232. // Camera
  21233. this.updateTransformMatrix();
  21234. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  21235. }
  21236. }
  21237. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  21238. this._intermediateRendering = false;
  21239. this._renderId++;
  21240. }
  21241. // Restore back buffer
  21242. if (this.customRenderTargets.length > 0) {
  21243. engine.restoreDefaultFramebuffer();
  21244. }
  21245. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  21246. this.activeCamera = currentActiveCamera;
  21247. // Procedural textures
  21248. if (this.proceduralTexturesEnabled) {
  21249. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  21250. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  21251. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  21252. if (proceduralTexture._shouldRender()) {
  21253. proceduralTexture.render();
  21254. }
  21255. }
  21256. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  21257. }
  21258. // Clear
  21259. if (this.autoClearDepthAndStencil || this.autoClear) {
  21260. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  21261. }
  21262. // Shadows
  21263. if (this.shadowsEnabled) {
  21264. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  21265. var light = this.lights[lightIndex];
  21266. var shadowGenerator = light.getShadowGenerator();
  21267. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  21268. var shadowMap = (shadowGenerator.getShadowMap());
  21269. if (this.textures.indexOf(shadowMap) !== -1) {
  21270. this._renderTargets.push(shadowMap);
  21271. }
  21272. }
  21273. }
  21274. }
  21275. // Depth renderer
  21276. if (this._depthRenderer) {
  21277. this._renderTargets.push(this._depthRenderer.getDepthMap());
  21278. }
  21279. // Geometry renderer
  21280. if (this._geometryBufferRenderer) {
  21281. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  21282. }
  21283. // RenderPipeline
  21284. if (this._postProcessRenderPipelineManager) {
  21285. this._postProcessRenderPipelineManager.update();
  21286. }
  21287. // Multi-cameras?
  21288. if (this.activeCameras.length > 0) {
  21289. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  21290. if (cameraIndex > 0) {
  21291. this._engine.clear(null, false, true, true);
  21292. }
  21293. this._processSubCameras(this.activeCameras[cameraIndex]);
  21294. }
  21295. }
  21296. else {
  21297. if (!this.activeCamera) {
  21298. throw new Error("No camera defined");
  21299. }
  21300. this._processSubCameras(this.activeCamera);
  21301. }
  21302. // Intersection checks
  21303. this._checkIntersections();
  21304. // Update the audio listener attached to the camera
  21305. if (BABYLON.AudioEngine) {
  21306. this._updateAudioParameters();
  21307. }
  21308. // After render
  21309. if (this.afterRender) {
  21310. this.afterRender();
  21311. }
  21312. this.onAfterRenderObservable.notifyObservers(this);
  21313. // Cleaning
  21314. for (var index = 0; index < this._toBeDisposed.length; index++) {
  21315. var data = this._toBeDisposed.data[index];
  21316. if (data) {
  21317. data.dispose();
  21318. }
  21319. this._toBeDisposed[index] = null;
  21320. }
  21321. this._toBeDisposed.reset();
  21322. if (this.dumpNextRenderTargets) {
  21323. this.dumpNextRenderTargets = false;
  21324. }
  21325. this._activeBones.addCount(0, true);
  21326. this._activeIndices.addCount(0, true);
  21327. this._activeParticles.addCount(0, true);
  21328. };
  21329. Scene.prototype._updateAudioParameters = function () {
  21330. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  21331. return;
  21332. }
  21333. var listeningCamera;
  21334. var audioEngine = BABYLON.Engine.audioEngine;
  21335. if (this.activeCameras.length > 0) {
  21336. listeningCamera = this.activeCameras[0];
  21337. }
  21338. else {
  21339. listeningCamera = this.activeCamera;
  21340. }
  21341. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  21342. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  21343. // for VR cameras
  21344. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  21345. listeningCamera = listeningCamera.rigCameras[0];
  21346. }
  21347. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  21348. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  21349. cameraDirection.normalize();
  21350. // To avoid some errors on GearVR
  21351. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  21352. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  21353. }
  21354. var i;
  21355. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  21356. var sound = this.mainSoundTrack.soundCollection[i];
  21357. if (sound.useCustomAttenuation) {
  21358. sound.updateDistanceFromListener();
  21359. }
  21360. }
  21361. for (i = 0; i < this.soundTracks.length; i++) {
  21362. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  21363. sound = this.soundTracks[i].soundCollection[j];
  21364. if (sound.useCustomAttenuation) {
  21365. sound.updateDistanceFromListener();
  21366. }
  21367. }
  21368. }
  21369. }
  21370. };
  21371. Object.defineProperty(Scene.prototype, "audioEnabled", {
  21372. // Audio
  21373. get: function () {
  21374. return this._audioEnabled;
  21375. },
  21376. set: function (value) {
  21377. this._audioEnabled = value;
  21378. if (BABYLON.AudioEngine) {
  21379. if (this._audioEnabled) {
  21380. this._enableAudio();
  21381. }
  21382. else {
  21383. this._disableAudio();
  21384. }
  21385. }
  21386. },
  21387. enumerable: true,
  21388. configurable: true
  21389. });
  21390. Scene.prototype._disableAudio = function () {
  21391. var i;
  21392. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  21393. this.mainSoundTrack.soundCollection[i].pause();
  21394. }
  21395. for (i = 0; i < this.soundTracks.length; i++) {
  21396. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  21397. this.soundTracks[i].soundCollection[j].pause();
  21398. }
  21399. }
  21400. };
  21401. Scene.prototype._enableAudio = function () {
  21402. var i;
  21403. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  21404. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  21405. this.mainSoundTrack.soundCollection[i].play();
  21406. }
  21407. }
  21408. for (i = 0; i < this.soundTracks.length; i++) {
  21409. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  21410. if (this.soundTracks[i].soundCollection[j].isPaused) {
  21411. this.soundTracks[i].soundCollection[j].play();
  21412. }
  21413. }
  21414. }
  21415. };
  21416. Object.defineProperty(Scene.prototype, "headphone", {
  21417. get: function () {
  21418. return this._headphone;
  21419. },
  21420. set: function (value) {
  21421. this._headphone = value;
  21422. if (BABYLON.AudioEngine) {
  21423. if (this._headphone) {
  21424. this._switchAudioModeForHeadphones();
  21425. }
  21426. else {
  21427. this._switchAudioModeForNormalSpeakers();
  21428. }
  21429. }
  21430. },
  21431. enumerable: true,
  21432. configurable: true
  21433. });
  21434. Scene.prototype._switchAudioModeForHeadphones = function () {
  21435. this.mainSoundTrack.switchPanningModelToHRTF();
  21436. for (var i = 0; i < this.soundTracks.length; i++) {
  21437. this.soundTracks[i].switchPanningModelToHRTF();
  21438. }
  21439. };
  21440. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  21441. this.mainSoundTrack.switchPanningModelToEqualPower();
  21442. for (var i = 0; i < this.soundTracks.length; i++) {
  21443. this.soundTracks[i].switchPanningModelToEqualPower();
  21444. }
  21445. };
  21446. Scene.prototype.enableDepthRenderer = function () {
  21447. if (this._depthRenderer) {
  21448. return this._depthRenderer;
  21449. }
  21450. this._depthRenderer = new BABYLON.DepthRenderer(this);
  21451. return this._depthRenderer;
  21452. };
  21453. Scene.prototype.disableDepthRenderer = function () {
  21454. if (!this._depthRenderer) {
  21455. return;
  21456. }
  21457. this._depthRenderer.dispose();
  21458. this._depthRenderer = null;
  21459. };
  21460. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  21461. if (ratio === void 0) { ratio = 1; }
  21462. if (this._geometryBufferRenderer) {
  21463. return this._geometryBufferRenderer;
  21464. }
  21465. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  21466. if (!this._geometryBufferRenderer.isSupported) {
  21467. this._geometryBufferRenderer = null;
  21468. }
  21469. return this._geometryBufferRenderer;
  21470. };
  21471. Scene.prototype.disableGeometryBufferRenderer = function () {
  21472. if (!this._geometryBufferRenderer) {
  21473. return;
  21474. }
  21475. this._geometryBufferRenderer.dispose();
  21476. this._geometryBufferRenderer = null;
  21477. };
  21478. Scene.prototype.freezeMaterials = function () {
  21479. for (var i = 0; i < this.materials.length; i++) {
  21480. this.materials[i].freeze();
  21481. }
  21482. };
  21483. Scene.prototype.unfreezeMaterials = function () {
  21484. for (var i = 0; i < this.materials.length; i++) {
  21485. this.materials[i].unfreeze();
  21486. }
  21487. };
  21488. Scene.prototype.dispose = function () {
  21489. this.beforeRender = null;
  21490. this.afterRender = null;
  21491. this.skeletons = [];
  21492. this.morphTargetManagers = [];
  21493. this.importedMeshesFiles = new Array();
  21494. this.stopAllAnimations();
  21495. this.resetCachedMaterial();
  21496. if (this._depthRenderer) {
  21497. this._depthRenderer.dispose();
  21498. }
  21499. if (this._gamepadManager) {
  21500. this._gamepadManager.dispose();
  21501. this._gamepadManager = null;
  21502. }
  21503. // Smart arrays
  21504. if (this.activeCamera) {
  21505. this.activeCamera._activeMeshes.dispose();
  21506. this.activeCamera = null;
  21507. }
  21508. this._activeMeshes.dispose();
  21509. this._renderingManager.dispose();
  21510. this._processedMaterials.dispose();
  21511. this._activeParticleSystems.dispose();
  21512. this._activeSkeletons.dispose();
  21513. this._softwareSkinnedMeshes.dispose();
  21514. this._renderTargets.dispose();
  21515. if (this._boundingBoxRenderer) {
  21516. this._boundingBoxRenderer.dispose();
  21517. }
  21518. this._meshesForIntersections.dispose();
  21519. this._toBeDisposed.dispose();
  21520. // Abort active requests
  21521. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  21522. var request = _a[_i];
  21523. request.abort();
  21524. }
  21525. // Debug layer
  21526. if (this._debugLayer) {
  21527. this._debugLayer.hide();
  21528. }
  21529. // Events
  21530. this.onDisposeObservable.notifyObservers(this);
  21531. this.onDisposeObservable.clear();
  21532. this.onBeforeRenderObservable.clear();
  21533. this.onAfterRenderObservable.clear();
  21534. this.OnBeforeRenderTargetsRenderObservable.clear();
  21535. this.OnAfterRenderTargetsRenderObservable.clear();
  21536. this.onAfterStepObservable.clear();
  21537. this.onBeforeStepObservable.clear();
  21538. this.onBeforeActiveMeshesEvaluationObservable.clear();
  21539. this.onAfterActiveMeshesEvaluationObservable.clear();
  21540. this.onBeforeParticlesRenderingObservable.clear();
  21541. this.onAfterParticlesRenderingObservable.clear();
  21542. this.onBeforeSpritesRenderingObservable.clear();
  21543. this.onAfterSpritesRenderingObservable.clear();
  21544. this.onBeforeDrawPhaseObservable.clear();
  21545. this.onAfterDrawPhaseObservable.clear();
  21546. this.onBeforePhysicsObservable.clear();
  21547. this.onAfterPhysicsObservable.clear();
  21548. this.onBeforeAnimationsObservable.clear();
  21549. this.onAfterAnimationsObservable.clear();
  21550. this.onDataLoadedObservable.clear();
  21551. this.detachControl();
  21552. // Release sounds & sounds tracks
  21553. if (BABYLON.AudioEngine) {
  21554. this.disposeSounds();
  21555. }
  21556. // VR Helper
  21557. if (this.VRHelper) {
  21558. this.VRHelper.dispose();
  21559. }
  21560. // Detach cameras
  21561. var canvas = this._engine.getRenderingCanvas();
  21562. if (canvas) {
  21563. var index;
  21564. for (index = 0; index < this.cameras.length; index++) {
  21565. this.cameras[index].detachControl(canvas);
  21566. }
  21567. }
  21568. // Release animation groups
  21569. while (this.animationGroups.length) {
  21570. this.animationGroups[0].dispose();
  21571. }
  21572. // Release lights
  21573. while (this.lights.length) {
  21574. this.lights[0].dispose();
  21575. }
  21576. // Release meshes
  21577. while (this.meshes.length) {
  21578. this.meshes[0].dispose(true);
  21579. }
  21580. while (this.transformNodes.length) {
  21581. this.removeTransformNode(this.transformNodes[0]);
  21582. }
  21583. // Release cameras
  21584. while (this.cameras.length) {
  21585. this.cameras[0].dispose();
  21586. }
  21587. // Release materials
  21588. if (this.defaultMaterial) {
  21589. this.defaultMaterial.dispose();
  21590. }
  21591. while (this.multiMaterials.length) {
  21592. this.multiMaterials[0].dispose();
  21593. }
  21594. while (this.materials.length) {
  21595. this.materials[0].dispose();
  21596. }
  21597. // Release particles
  21598. while (this.particleSystems.length) {
  21599. this.particleSystems[0].dispose();
  21600. }
  21601. // Release sprites
  21602. while (this.spriteManagers.length) {
  21603. this.spriteManagers[0].dispose();
  21604. }
  21605. // Release postProcesses
  21606. while (this.postProcesses.length) {
  21607. this.postProcesses[0].dispose();
  21608. }
  21609. // Release layers
  21610. while (this.layers.length) {
  21611. this.layers[0].dispose();
  21612. }
  21613. while (this.highlightLayers.length) {
  21614. this.highlightLayers[0].dispose();
  21615. }
  21616. // Release textures
  21617. while (this.textures.length) {
  21618. this.textures[0].dispose();
  21619. }
  21620. // Release UBO
  21621. this._sceneUbo.dispose();
  21622. if (this._alternateSceneUbo) {
  21623. this._alternateSceneUbo.dispose();
  21624. }
  21625. // Post-processes
  21626. this.postProcessManager.dispose();
  21627. if (this._postProcessRenderPipelineManager) {
  21628. this._postProcessRenderPipelineManager.dispose();
  21629. }
  21630. // Physics
  21631. if (this._physicsEngine) {
  21632. this.disablePhysicsEngine();
  21633. }
  21634. // Remove from engine
  21635. index = this._engine.scenes.indexOf(this);
  21636. if (index > -1) {
  21637. this._engine.scenes.splice(index, 1);
  21638. }
  21639. this._engine.wipeCaches(true);
  21640. this._isDisposed = true;
  21641. };
  21642. Object.defineProperty(Scene.prototype, "isDisposed", {
  21643. get: function () {
  21644. return this._isDisposed;
  21645. },
  21646. enumerable: true,
  21647. configurable: true
  21648. });
  21649. // Release sounds & sounds tracks
  21650. Scene.prototype.disposeSounds = function () {
  21651. if (!this._mainSoundTrack) {
  21652. return;
  21653. }
  21654. this.mainSoundTrack.dispose();
  21655. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  21656. this.soundTracks[scIndex].dispose();
  21657. }
  21658. };
  21659. // Octrees
  21660. Scene.prototype.getWorldExtends = function () {
  21661. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21662. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  21663. for (var index = 0; index < this.meshes.length; index++) {
  21664. var mesh = this.meshes[index];
  21665. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  21666. continue;
  21667. }
  21668. mesh.computeWorldMatrix(true);
  21669. var boundingInfo = mesh.getBoundingInfo();
  21670. var minBox = boundingInfo.boundingBox.minimumWorld;
  21671. var maxBox = boundingInfo.boundingBox.maximumWorld;
  21672. BABYLON.Tools.CheckExtends(minBox, min, max);
  21673. BABYLON.Tools.CheckExtends(maxBox, min, max);
  21674. }
  21675. return {
  21676. min: min,
  21677. max: max
  21678. };
  21679. };
  21680. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  21681. if (maxCapacity === void 0) { maxCapacity = 64; }
  21682. if (maxDepth === void 0) { maxDepth = 2; }
  21683. if (!this._selectionOctree) {
  21684. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  21685. }
  21686. var worldExtends = this.getWorldExtends();
  21687. // Update octree
  21688. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  21689. return this._selectionOctree;
  21690. };
  21691. // Picking
  21692. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  21693. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  21694. var result = BABYLON.Ray.Zero();
  21695. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  21696. return result;
  21697. };
  21698. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  21699. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  21700. var engine = this._engine;
  21701. if (!camera) {
  21702. if (!this.activeCamera)
  21703. throw new Error("Active camera not set");
  21704. camera = this.activeCamera;
  21705. }
  21706. var cameraViewport = camera.viewport;
  21707. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  21708. // Moving coordinates to local viewport world
  21709. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  21710. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  21711. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  21712. return this;
  21713. };
  21714. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  21715. var result = BABYLON.Ray.Zero();
  21716. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  21717. return result;
  21718. };
  21719. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  21720. if (!BABYLON.PickingInfo) {
  21721. return this;
  21722. }
  21723. var engine = this._engine;
  21724. if (!camera) {
  21725. if (!this.activeCamera)
  21726. throw new Error("Active camera not set");
  21727. camera = this.activeCamera;
  21728. }
  21729. var cameraViewport = camera.viewport;
  21730. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  21731. var identity = BABYLON.Matrix.Identity();
  21732. // Moving coordinates to local viewport world
  21733. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  21734. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  21735. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  21736. return this;
  21737. };
  21738. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  21739. if (!BABYLON.PickingInfo) {
  21740. return null;
  21741. }
  21742. var pickingInfo = null;
  21743. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  21744. var mesh = this.meshes[meshIndex];
  21745. if (predicate) {
  21746. if (!predicate(mesh)) {
  21747. continue;
  21748. }
  21749. }
  21750. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  21751. continue;
  21752. }
  21753. var world = mesh.getWorldMatrix();
  21754. var ray = rayFunction(world);
  21755. var result = mesh.intersects(ray, fastCheck);
  21756. if (!result || !result.hit)
  21757. continue;
  21758. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  21759. continue;
  21760. pickingInfo = result;
  21761. if (fastCheck) {
  21762. break;
  21763. }
  21764. }
  21765. return pickingInfo || new BABYLON.PickingInfo();
  21766. };
  21767. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  21768. if (!BABYLON.PickingInfo) {
  21769. return null;
  21770. }
  21771. var pickingInfos = new Array();
  21772. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  21773. var mesh = this.meshes[meshIndex];
  21774. if (predicate) {
  21775. if (!predicate(mesh)) {
  21776. continue;
  21777. }
  21778. }
  21779. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  21780. continue;
  21781. }
  21782. var world = mesh.getWorldMatrix();
  21783. var ray = rayFunction(world);
  21784. var result = mesh.intersects(ray, false);
  21785. if (!result || !result.hit)
  21786. continue;
  21787. pickingInfos.push(result);
  21788. }
  21789. return pickingInfos;
  21790. };
  21791. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  21792. if (!BABYLON.PickingInfo) {
  21793. return null;
  21794. }
  21795. var pickingInfo = null;
  21796. if (!camera) {
  21797. if (!this.activeCamera) {
  21798. return null;
  21799. }
  21800. camera = this.activeCamera;
  21801. }
  21802. if (this.spriteManagers.length > 0) {
  21803. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  21804. var spriteManager = this.spriteManagers[spriteIndex];
  21805. if (!spriteManager.isPickable) {
  21806. continue;
  21807. }
  21808. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  21809. if (!result || !result.hit)
  21810. continue;
  21811. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  21812. continue;
  21813. pickingInfo = result;
  21814. if (fastCheck) {
  21815. break;
  21816. }
  21817. }
  21818. }
  21819. return pickingInfo || new BABYLON.PickingInfo();
  21820. };
  21821. /** Launch a ray to try to pick a mesh in the scene
  21822. * @param x position on screen
  21823. * @param y position on screen
  21824. * @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
  21825. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  21826. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  21827. */
  21828. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  21829. var _this = this;
  21830. if (!BABYLON.PickingInfo) {
  21831. return null;
  21832. }
  21833. return this._internalPick(function (world) {
  21834. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  21835. return _this._tempPickingRay;
  21836. }, predicate, fastCheck);
  21837. };
  21838. /** Launch a ray to try to pick a sprite in the scene
  21839. * @param x position on screen
  21840. * @param y position on screen
  21841. * @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
  21842. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  21843. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  21844. */
  21845. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  21846. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  21847. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  21848. };
  21849. /** Use the given ray to pick a mesh in the scene
  21850. * @param ray The ray to use to pick meshes
  21851. * @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
  21852. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  21853. */
  21854. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  21855. var _this = this;
  21856. return this._internalPick(function (world) {
  21857. if (!_this._pickWithRayInverseMatrix) {
  21858. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  21859. }
  21860. world.invertToRef(_this._pickWithRayInverseMatrix);
  21861. if (!_this._cachedRayForTransform) {
  21862. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  21863. }
  21864. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  21865. return _this._cachedRayForTransform;
  21866. }, predicate, fastCheck);
  21867. };
  21868. /**
  21869. * Launch a ray to try to pick a mesh in the scene
  21870. * @param x X position on screen
  21871. * @param y Y position on screen
  21872. * @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
  21873. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  21874. */
  21875. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  21876. var _this = this;
  21877. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  21878. };
  21879. /**
  21880. * Launch a ray to try to pick a mesh in the scene
  21881. * @param ray Ray to use
  21882. * @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
  21883. */
  21884. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  21885. var _this = this;
  21886. return this._internalMultiPick(function (world) {
  21887. if (!_this._pickWithRayInverseMatrix) {
  21888. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  21889. }
  21890. world.invertToRef(_this._pickWithRayInverseMatrix);
  21891. if (!_this._cachedRayForTransform) {
  21892. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  21893. }
  21894. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  21895. return _this._cachedRayForTransform;
  21896. }, predicate);
  21897. };
  21898. Scene.prototype.setPointerOverMesh = function (mesh) {
  21899. if (this._pointerOverMesh === mesh) {
  21900. return;
  21901. }
  21902. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  21903. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  21904. }
  21905. this._pointerOverMesh = mesh;
  21906. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  21907. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  21908. }
  21909. };
  21910. Scene.prototype.getPointerOverMesh = function () {
  21911. return this._pointerOverMesh;
  21912. };
  21913. Scene.prototype.setPointerOverSprite = function (sprite) {
  21914. if (this._pointerOverSprite === sprite) {
  21915. return;
  21916. }
  21917. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  21918. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  21919. }
  21920. this._pointerOverSprite = sprite;
  21921. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  21922. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  21923. }
  21924. };
  21925. Scene.prototype.getPointerOverSprite = function () {
  21926. return this._pointerOverSprite;
  21927. };
  21928. // Physics
  21929. Scene.prototype.getPhysicsEngine = function () {
  21930. return this._physicsEngine;
  21931. };
  21932. /**
  21933. * Enables physics to the current scene
  21934. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  21935. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  21936. * @return {boolean} was the physics engine initialized
  21937. */
  21938. Scene.prototype.enablePhysics = function (gravity, plugin) {
  21939. if (gravity === void 0) { gravity = null; }
  21940. if (this._physicsEngine) {
  21941. return true;
  21942. }
  21943. try {
  21944. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  21945. return true;
  21946. }
  21947. catch (e) {
  21948. BABYLON.Tools.Error(e.message);
  21949. return false;
  21950. }
  21951. };
  21952. Scene.prototype.disablePhysicsEngine = function () {
  21953. if (!this._physicsEngine) {
  21954. return;
  21955. }
  21956. this._physicsEngine.dispose();
  21957. this._physicsEngine = null;
  21958. };
  21959. Scene.prototype.isPhysicsEnabled = function () {
  21960. return this._physicsEngine !== undefined;
  21961. };
  21962. Scene.prototype.deleteCompoundImpostor = function (compound) {
  21963. var mesh = compound.parts[0].mesh;
  21964. if (mesh.physicsImpostor) {
  21965. mesh.physicsImpostor.dispose();
  21966. mesh.physicsImpostor = null;
  21967. }
  21968. };
  21969. // Misc.
  21970. Scene.prototype._rebuildGeometries = function () {
  21971. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  21972. var geometry = _a[_i];
  21973. geometry._rebuild();
  21974. }
  21975. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  21976. var mesh = _c[_b];
  21977. mesh._rebuild();
  21978. }
  21979. if (this.postProcessManager) {
  21980. this.postProcessManager._rebuild();
  21981. }
  21982. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  21983. var layer = _e[_d];
  21984. layer._rebuild();
  21985. }
  21986. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  21987. var highlightLayer = _g[_f];
  21988. highlightLayer._rebuild();
  21989. }
  21990. if (this._boundingBoxRenderer) {
  21991. this._boundingBoxRenderer._rebuild();
  21992. }
  21993. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  21994. var system = _j[_h];
  21995. system.rebuild();
  21996. }
  21997. if (this._postProcessRenderPipelineManager) {
  21998. this._postProcessRenderPipelineManager._rebuild();
  21999. }
  22000. };
  22001. Scene.prototype._rebuildTextures = function () {
  22002. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  22003. var texture = _a[_i];
  22004. texture._rebuild();
  22005. }
  22006. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22007. };
  22008. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  22009. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  22010. if (replace === void 0) { replace = false; }
  22011. if (attachCameraControls === void 0) { attachCameraControls = false; }
  22012. // Dispose existing camera or light in replace mode.
  22013. if (replace) {
  22014. if (this.activeCamera) {
  22015. this.activeCamera.dispose();
  22016. this.activeCamera = null;
  22017. }
  22018. if (this.lights) {
  22019. for (var i = 0; i < this.lights.length; i++) {
  22020. this.lights[i].dispose();
  22021. }
  22022. }
  22023. }
  22024. // Light
  22025. if (this.lights.length === 0) {
  22026. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  22027. }
  22028. // Camera
  22029. if (!this.activeCamera) {
  22030. var worldExtends = this.getWorldExtends();
  22031. var worldSize = worldExtends.max.subtract(worldExtends.min);
  22032. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  22033. var camera;
  22034. var radius = worldSize.length() * 1.5;
  22035. if (createArcRotateCamera) {
  22036. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  22037. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  22038. arcRotateCamera.wheelPrecision = 100 / radius;
  22039. camera = arcRotateCamera;
  22040. }
  22041. else {
  22042. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  22043. freeCamera.setTarget(worldCenter);
  22044. camera = freeCamera;
  22045. }
  22046. camera.minZ = radius * 0.01;
  22047. camera.maxZ = radius * 1000;
  22048. camera.speed = radius * 0.2;
  22049. this.activeCamera = camera;
  22050. var canvas = this.getEngine().getRenderingCanvas();
  22051. if (attachCameraControls && canvas) {
  22052. camera.attachControl(canvas);
  22053. }
  22054. }
  22055. };
  22056. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  22057. if (pbr === void 0) { pbr = false; }
  22058. if (scale === void 0) { scale = 1000; }
  22059. if (blur === void 0) { blur = 0; }
  22060. if (environmentTexture) {
  22061. this.environmentTexture = environmentTexture;
  22062. }
  22063. if (!this.environmentTexture) {
  22064. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  22065. return null;
  22066. }
  22067. // Skybox
  22068. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  22069. if (pbr) {
  22070. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  22071. hdrSkyboxMaterial.backFaceCulling = false;
  22072. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  22073. if (hdrSkyboxMaterial.reflectionTexture) {
  22074. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  22075. }
  22076. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  22077. hdrSkyboxMaterial.disableLighting = true;
  22078. hdrSkyboxMaterial.twoSidedLighting = true;
  22079. hdrSkybox.infiniteDistance = true;
  22080. hdrSkybox.material = hdrSkyboxMaterial;
  22081. }
  22082. else {
  22083. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  22084. skyboxMaterial.backFaceCulling = false;
  22085. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  22086. if (skyboxMaterial.reflectionTexture) {
  22087. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  22088. }
  22089. skyboxMaterial.disableLighting = true;
  22090. hdrSkybox.infiniteDistance = true;
  22091. hdrSkybox.material = skyboxMaterial;
  22092. }
  22093. return hdrSkybox;
  22094. };
  22095. Scene.prototype.createDefaultEnvironment = function (options) {
  22096. if (BABYLON.EnvironmentHelper) {
  22097. return new BABYLON.EnvironmentHelper(options, this);
  22098. }
  22099. return null;
  22100. };
  22101. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  22102. if (webVROptions === void 0) { webVROptions = {}; }
  22103. return new BABYLON.VRExperienceHelper(this, webVROptions);
  22104. };
  22105. // Tags
  22106. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  22107. if (tagsQuery === undefined) {
  22108. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  22109. return list;
  22110. }
  22111. var listByTags = [];
  22112. forEach = forEach || (function (item) { return; });
  22113. for (var i in list) {
  22114. var item = list[i];
  22115. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  22116. listByTags.push(item);
  22117. forEach(item);
  22118. }
  22119. }
  22120. return listByTags;
  22121. };
  22122. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  22123. return this._getByTags(this.meshes, tagsQuery, forEach);
  22124. };
  22125. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  22126. return this._getByTags(this.cameras, tagsQuery, forEach);
  22127. };
  22128. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  22129. return this._getByTags(this.lights, tagsQuery, forEach);
  22130. };
  22131. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  22132. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  22133. };
  22134. /**
  22135. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  22136. * This allowed control for front to back rendering or reversly depending of the special needs.
  22137. *
  22138. * @param renderingGroupId The rendering group id corresponding to its index
  22139. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  22140. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  22141. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  22142. */
  22143. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22144. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22145. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22146. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22147. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  22148. };
  22149. /**
  22150. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  22151. *
  22152. * @param renderingGroupId The rendering group id corresponding to its index
  22153. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  22154. * @param depth Automatically clears depth between groups if true and autoClear is true.
  22155. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  22156. */
  22157. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  22158. if (depth === void 0) { depth = true; }
  22159. if (stencil === void 0) { stencil = true; }
  22160. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  22161. };
  22162. /**
  22163. * Will flag all materials as dirty to trigger new shader compilation
  22164. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  22165. */
  22166. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  22167. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  22168. var material = _a[_i];
  22169. if (predicate && !predicate(material)) {
  22170. continue;
  22171. }
  22172. material.markAsDirty(flag);
  22173. }
  22174. };
  22175. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  22176. var _this = this;
  22177. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  22178. this._activeRequests.push(request);
  22179. request.onCompleteObservable.add(function (request) {
  22180. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  22181. });
  22182. return request;
  22183. };
  22184. // Statics
  22185. Scene._FOGMODE_NONE = 0;
  22186. Scene._FOGMODE_EXP = 1;
  22187. Scene._FOGMODE_EXP2 = 2;
  22188. Scene._FOGMODE_LINEAR = 3;
  22189. Scene._uniqueIdCounter = 0;
  22190. Scene.MinDeltaTime = 1.0;
  22191. Scene.MaxDeltaTime = 1000.0;
  22192. /** The distance in pixel that you have to move to prevent some events */
  22193. Scene.DragMovementThreshold = 10; // in pixels
  22194. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  22195. Scene.LongPressDelay = 500; // in milliseconds
  22196. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  22197. Scene.DoubleClickDelay = 300; // in milliseconds
  22198. /** If you need to check double click without raising a single click at first click, enable this flag */
  22199. Scene.ExclusiveDoubleClickMode = false;
  22200. return Scene;
  22201. }());
  22202. BABYLON.Scene = Scene;
  22203. })(BABYLON || (BABYLON = {}));
  22204. //# sourceMappingURL=babylon.scene.js.map
  22205. var BABYLON;
  22206. (function (BABYLON) {
  22207. var Buffer = /** @class */ (function () {
  22208. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  22209. if (instanced === void 0) { instanced = false; }
  22210. if (engine instanceof BABYLON.Mesh) {
  22211. this._engine = engine.getScene().getEngine();
  22212. }
  22213. else {
  22214. this._engine = engine;
  22215. }
  22216. this._updatable = updatable;
  22217. this._data = data;
  22218. this._strideSize = stride;
  22219. if (!postponeInternalCreation) {
  22220. this.create();
  22221. }
  22222. this._instanced = instanced;
  22223. this._instanceDivisor = instanced ? 1 : 0;
  22224. }
  22225. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  22226. // a lot of these parameters are ignored as they are overriden by the buffer
  22227. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  22228. };
  22229. // Properties
  22230. Buffer.prototype.isUpdatable = function () {
  22231. return this._updatable;
  22232. };
  22233. Buffer.prototype.getData = function () {
  22234. return this._data;
  22235. };
  22236. Buffer.prototype.getBuffer = function () {
  22237. return this._buffer;
  22238. };
  22239. Buffer.prototype.getStrideSize = function () {
  22240. return this._strideSize;
  22241. };
  22242. Buffer.prototype.getIsInstanced = function () {
  22243. return this._instanced;
  22244. };
  22245. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  22246. get: function () {
  22247. return this._instanceDivisor;
  22248. },
  22249. set: function (value) {
  22250. this._instanceDivisor = value;
  22251. if (value == 0) {
  22252. this._instanced = false;
  22253. }
  22254. else {
  22255. this._instanced = true;
  22256. }
  22257. },
  22258. enumerable: true,
  22259. configurable: true
  22260. });
  22261. // Methods
  22262. Buffer.prototype.create = function (data) {
  22263. if (data === void 0) { data = null; }
  22264. if (!data && this._buffer) {
  22265. return; // nothing to do
  22266. }
  22267. data = data || this._data;
  22268. if (!data) {
  22269. return;
  22270. }
  22271. if (!this._buffer) {
  22272. if (this._updatable) {
  22273. this._buffer = this._engine.createDynamicVertexBuffer(data);
  22274. this._data = data;
  22275. }
  22276. else {
  22277. this._buffer = this._engine.createVertexBuffer(data);
  22278. }
  22279. }
  22280. else if (this._updatable) {
  22281. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  22282. this._data = data;
  22283. }
  22284. };
  22285. Buffer.prototype._rebuild = function () {
  22286. this._buffer = null;
  22287. this.create(this._data);
  22288. };
  22289. Buffer.prototype.update = function (data) {
  22290. this.create(data);
  22291. };
  22292. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  22293. if (!this._buffer) {
  22294. return;
  22295. }
  22296. if (this._updatable) {
  22297. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  22298. this._data = null;
  22299. }
  22300. };
  22301. Buffer.prototype.dispose = function () {
  22302. if (!this._buffer) {
  22303. return;
  22304. }
  22305. if (this._engine._releaseBuffer(this._buffer)) {
  22306. this._buffer = null;
  22307. }
  22308. };
  22309. return Buffer;
  22310. }());
  22311. BABYLON.Buffer = Buffer;
  22312. })(BABYLON || (BABYLON = {}));
  22313. //# sourceMappingURL=babylon.buffer.js.map
  22314. var BABYLON;
  22315. (function (BABYLON) {
  22316. var VertexBuffer = /** @class */ (function () {
  22317. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  22318. if (!stride) {
  22319. // Deduce stride from kind
  22320. switch (kind) {
  22321. case VertexBuffer.PositionKind:
  22322. stride = 3;
  22323. break;
  22324. case VertexBuffer.NormalKind:
  22325. stride = 3;
  22326. break;
  22327. case VertexBuffer.UVKind:
  22328. case VertexBuffer.UV2Kind:
  22329. case VertexBuffer.UV3Kind:
  22330. case VertexBuffer.UV4Kind:
  22331. case VertexBuffer.UV5Kind:
  22332. case VertexBuffer.UV6Kind:
  22333. stride = 2;
  22334. break;
  22335. case VertexBuffer.TangentKind:
  22336. case VertexBuffer.ColorKind:
  22337. stride = 4;
  22338. break;
  22339. case VertexBuffer.MatricesIndicesKind:
  22340. case VertexBuffer.MatricesIndicesExtraKind:
  22341. stride = 4;
  22342. break;
  22343. case VertexBuffer.MatricesWeightsKind:
  22344. case VertexBuffer.MatricesWeightsExtraKind:
  22345. default:
  22346. stride = 4;
  22347. break;
  22348. }
  22349. }
  22350. if (data instanceof BABYLON.Buffer) {
  22351. if (!stride) {
  22352. stride = data.getStrideSize();
  22353. }
  22354. this._buffer = data;
  22355. this._ownsBuffer = false;
  22356. }
  22357. else {
  22358. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  22359. this._ownsBuffer = true;
  22360. }
  22361. this._stride = stride;
  22362. this._offset = offset ? offset : 0;
  22363. this._size = size ? size : stride;
  22364. this._kind = kind;
  22365. }
  22366. VertexBuffer.prototype._rebuild = function () {
  22367. if (!this._buffer) {
  22368. return;
  22369. }
  22370. this._buffer._rebuild();
  22371. };
  22372. /**
  22373. * Returns the kind of the VertexBuffer (string).
  22374. */
  22375. VertexBuffer.prototype.getKind = function () {
  22376. return this._kind;
  22377. };
  22378. // Properties
  22379. /**
  22380. * Boolean : is the VertexBuffer updatable ?
  22381. */
  22382. VertexBuffer.prototype.isUpdatable = function () {
  22383. return this._buffer.isUpdatable();
  22384. };
  22385. /**
  22386. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  22387. */
  22388. VertexBuffer.prototype.getData = function () {
  22389. return this._buffer.getData();
  22390. };
  22391. /**
  22392. * Returns the WebGLBuffer associated to the VertexBuffer.
  22393. */
  22394. VertexBuffer.prototype.getBuffer = function () {
  22395. return this._buffer.getBuffer();
  22396. };
  22397. /**
  22398. * Returns the stride of the VertexBuffer (integer).
  22399. */
  22400. VertexBuffer.prototype.getStrideSize = function () {
  22401. return this._stride;
  22402. };
  22403. /**
  22404. * Returns the offset (integer).
  22405. */
  22406. VertexBuffer.prototype.getOffset = function () {
  22407. return this._offset;
  22408. };
  22409. /**
  22410. * Returns the VertexBuffer total size (integer).
  22411. */
  22412. VertexBuffer.prototype.getSize = function () {
  22413. return this._size;
  22414. };
  22415. /**
  22416. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  22417. */
  22418. VertexBuffer.prototype.getIsInstanced = function () {
  22419. return this._buffer.getIsInstanced();
  22420. };
  22421. /**
  22422. * Returns the instancing divisor, zero for non-instanced (integer).
  22423. */
  22424. VertexBuffer.prototype.getInstanceDivisor = function () {
  22425. return this._buffer.instanceDivisor;
  22426. };
  22427. // Methods
  22428. /**
  22429. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  22430. * Returns the created WebGLBuffer.
  22431. */
  22432. VertexBuffer.prototype.create = function (data) {
  22433. return this._buffer.create(data);
  22434. };
  22435. /**
  22436. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  22437. * Returns the updated WebGLBuffer.
  22438. */
  22439. VertexBuffer.prototype.update = function (data) {
  22440. return this._buffer.update(data);
  22441. };
  22442. /**
  22443. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  22444. * Returns the directly updated WebGLBuffer.
  22445. */
  22446. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  22447. return this._buffer.updateDirectly(data, offset);
  22448. };
  22449. /**
  22450. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  22451. */
  22452. VertexBuffer.prototype.dispose = function () {
  22453. if (this._ownsBuffer) {
  22454. this._buffer.dispose();
  22455. }
  22456. };
  22457. Object.defineProperty(VertexBuffer, "PositionKind", {
  22458. get: function () {
  22459. return VertexBuffer._PositionKind;
  22460. },
  22461. enumerable: true,
  22462. configurable: true
  22463. });
  22464. Object.defineProperty(VertexBuffer, "NormalKind", {
  22465. get: function () {
  22466. return VertexBuffer._NormalKind;
  22467. },
  22468. enumerable: true,
  22469. configurable: true
  22470. });
  22471. Object.defineProperty(VertexBuffer, "TangentKind", {
  22472. get: function () {
  22473. return VertexBuffer._TangentKind;
  22474. },
  22475. enumerable: true,
  22476. configurable: true
  22477. });
  22478. Object.defineProperty(VertexBuffer, "UVKind", {
  22479. get: function () {
  22480. return VertexBuffer._UVKind;
  22481. },
  22482. enumerable: true,
  22483. configurable: true
  22484. });
  22485. Object.defineProperty(VertexBuffer, "UV2Kind", {
  22486. get: function () {
  22487. return VertexBuffer._UV2Kind;
  22488. },
  22489. enumerable: true,
  22490. configurable: true
  22491. });
  22492. Object.defineProperty(VertexBuffer, "UV3Kind", {
  22493. get: function () {
  22494. return VertexBuffer._UV3Kind;
  22495. },
  22496. enumerable: true,
  22497. configurable: true
  22498. });
  22499. Object.defineProperty(VertexBuffer, "UV4Kind", {
  22500. get: function () {
  22501. return VertexBuffer._UV4Kind;
  22502. },
  22503. enumerable: true,
  22504. configurable: true
  22505. });
  22506. Object.defineProperty(VertexBuffer, "UV5Kind", {
  22507. get: function () {
  22508. return VertexBuffer._UV5Kind;
  22509. },
  22510. enumerable: true,
  22511. configurable: true
  22512. });
  22513. Object.defineProperty(VertexBuffer, "UV6Kind", {
  22514. get: function () {
  22515. return VertexBuffer._UV6Kind;
  22516. },
  22517. enumerable: true,
  22518. configurable: true
  22519. });
  22520. Object.defineProperty(VertexBuffer, "ColorKind", {
  22521. get: function () {
  22522. return VertexBuffer._ColorKind;
  22523. },
  22524. enumerable: true,
  22525. configurable: true
  22526. });
  22527. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  22528. get: function () {
  22529. return VertexBuffer._MatricesIndicesKind;
  22530. },
  22531. enumerable: true,
  22532. configurable: true
  22533. });
  22534. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  22535. get: function () {
  22536. return VertexBuffer._MatricesWeightsKind;
  22537. },
  22538. enumerable: true,
  22539. configurable: true
  22540. });
  22541. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  22542. get: function () {
  22543. return VertexBuffer._MatricesIndicesExtraKind;
  22544. },
  22545. enumerable: true,
  22546. configurable: true
  22547. });
  22548. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  22549. get: function () {
  22550. return VertexBuffer._MatricesWeightsExtraKind;
  22551. },
  22552. enumerable: true,
  22553. configurable: true
  22554. });
  22555. // Enums
  22556. VertexBuffer._PositionKind = "position";
  22557. VertexBuffer._NormalKind = "normal";
  22558. VertexBuffer._TangentKind = "tangent";
  22559. VertexBuffer._UVKind = "uv";
  22560. VertexBuffer._UV2Kind = "uv2";
  22561. VertexBuffer._UV3Kind = "uv3";
  22562. VertexBuffer._UV4Kind = "uv4";
  22563. VertexBuffer._UV5Kind = "uv5";
  22564. VertexBuffer._UV6Kind = "uv6";
  22565. VertexBuffer._ColorKind = "color";
  22566. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  22567. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  22568. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  22569. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  22570. return VertexBuffer;
  22571. }());
  22572. BABYLON.VertexBuffer = VertexBuffer;
  22573. })(BABYLON || (BABYLON = {}));
  22574. //# sourceMappingURL=babylon.vertexBuffer.js.map
  22575. var BABYLON;
  22576. (function (BABYLON) {
  22577. var InternalTexture = /** @class */ (function () {
  22578. function InternalTexture(engine, dataSource) {
  22579. this.onLoadedObservable = new BABYLON.Observable();
  22580. // Private
  22581. this._initialSlot = -1;
  22582. this._designatedSlot = -1;
  22583. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  22584. this._references = 1;
  22585. this._engine = engine;
  22586. this._dataSource = dataSource;
  22587. this._webGLTexture = engine._createTexture();
  22588. }
  22589. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  22590. get: function () {
  22591. return this._dataSource;
  22592. },
  22593. enumerable: true,
  22594. configurable: true
  22595. });
  22596. InternalTexture.prototype.incrementReferences = function () {
  22597. this._references++;
  22598. };
  22599. InternalTexture.prototype.updateSize = function (width, height, depth) {
  22600. if (depth === void 0) { depth = 1; }
  22601. this.width = width;
  22602. this.height = height;
  22603. this.depth = depth;
  22604. this.baseWidth = width;
  22605. this.baseHeight = height;
  22606. this.baseDepth = depth;
  22607. this._size = width * height * depth;
  22608. };
  22609. InternalTexture.prototype._rebuild = function () {
  22610. var _this = this;
  22611. var proxy;
  22612. this.isReady = false;
  22613. this._cachedCoordinatesMode = null;
  22614. this._cachedWrapU = null;
  22615. this._cachedWrapV = null;
  22616. this._cachedAnisotropicFilteringLevel = null;
  22617. switch (this._dataSource) {
  22618. case InternalTexture.DATASOURCE_TEMP:
  22619. return;
  22620. case InternalTexture.DATASOURCE_URL:
  22621. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  22622. _this.isReady = true;
  22623. }, null, this._buffer, undefined, this.format);
  22624. proxy._swapAndDie(this);
  22625. return;
  22626. case InternalTexture.DATASOURCE_RAW:
  22627. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  22628. proxy._swapAndDie(this);
  22629. this.isReady = true;
  22630. return;
  22631. case InternalTexture.DATASOURCE_RAW3D:
  22632. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  22633. proxy._swapAndDie(this);
  22634. this.isReady = true;
  22635. return;
  22636. case InternalTexture.DATASOURCE_DYNAMIC:
  22637. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  22638. proxy._swapAndDie(this);
  22639. // The engine will make sure to update content so no need to flag it as isReady = true
  22640. return;
  22641. case InternalTexture.DATASOURCE_RENDERTARGET:
  22642. var options = new BABYLON.RenderTargetCreationOptions();
  22643. options.generateDepthBuffer = this._generateDepthBuffer;
  22644. options.generateMipMaps = this.generateMipMaps;
  22645. options.generateStencilBuffer = this._generateStencilBuffer;
  22646. options.samplingMode = this.samplingMode;
  22647. options.type = this.type;
  22648. if (this.isCube) {
  22649. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  22650. }
  22651. else {
  22652. var size = {
  22653. width: this.width,
  22654. height: this.height
  22655. };
  22656. proxy = this._engine.createRenderTargetTexture(size, options);
  22657. }
  22658. proxy._swapAndDie(this);
  22659. this.isReady = true;
  22660. return;
  22661. case InternalTexture.DATASOURCE_CUBE:
  22662. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  22663. _this.isReady = true;
  22664. }, null, this.format, this._extension);
  22665. proxy._swapAndDie(this);
  22666. return;
  22667. case InternalTexture.DATASOURCE_CUBERAW:
  22668. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  22669. proxy._swapAndDie(this);
  22670. this.isReady = true;
  22671. return;
  22672. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  22673. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  22674. if (proxy) {
  22675. proxy._swapAndDie(_this);
  22676. }
  22677. _this.isReady = true;
  22678. }, null, this.format, this._extension);
  22679. return;
  22680. }
  22681. };
  22682. InternalTexture.prototype._swapAndDie = function (target) {
  22683. target._webGLTexture = this._webGLTexture;
  22684. if (this._framebuffer) {
  22685. target._framebuffer = this._framebuffer;
  22686. }
  22687. if (this._depthStencilBuffer) {
  22688. target._depthStencilBuffer = this._depthStencilBuffer;
  22689. }
  22690. if (this._lodTextureHigh) {
  22691. if (target._lodTextureHigh) {
  22692. target._lodTextureHigh.dispose();
  22693. }
  22694. target._lodTextureHigh = this._lodTextureHigh;
  22695. }
  22696. if (this._lodTextureMid) {
  22697. if (target._lodTextureMid) {
  22698. target._lodTextureMid.dispose();
  22699. }
  22700. target._lodTextureMid = this._lodTextureMid;
  22701. }
  22702. if (this._lodTextureLow) {
  22703. if (target._lodTextureLow) {
  22704. target._lodTextureLow.dispose();
  22705. }
  22706. target._lodTextureLow = this._lodTextureLow;
  22707. }
  22708. var cache = this._engine.getLoadedTexturesCache();
  22709. var index = cache.indexOf(this);
  22710. if (index !== -1) {
  22711. cache.splice(index, 1);
  22712. }
  22713. };
  22714. InternalTexture.prototype.dispose = function () {
  22715. if (!this._webGLTexture) {
  22716. return;
  22717. }
  22718. this._references--;
  22719. if (this._references === 0) {
  22720. this._engine._releaseTexture(this);
  22721. this._webGLTexture = null;
  22722. }
  22723. };
  22724. InternalTexture.DATASOURCE_UNKNOWN = 0;
  22725. InternalTexture.DATASOURCE_URL = 1;
  22726. InternalTexture.DATASOURCE_TEMP = 2;
  22727. InternalTexture.DATASOURCE_RAW = 3;
  22728. InternalTexture.DATASOURCE_DYNAMIC = 4;
  22729. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  22730. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  22731. InternalTexture.DATASOURCE_CUBE = 7;
  22732. InternalTexture.DATASOURCE_CUBERAW = 8;
  22733. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  22734. InternalTexture.DATASOURCE_RAW3D = 10;
  22735. return InternalTexture;
  22736. }());
  22737. BABYLON.InternalTexture = InternalTexture;
  22738. })(BABYLON || (BABYLON = {}));
  22739. //# sourceMappingURL=babylon.internalTexture.js.map
  22740. var BABYLON;
  22741. (function (BABYLON) {
  22742. var BaseTexture = /** @class */ (function () {
  22743. function BaseTexture(scene) {
  22744. this._hasAlpha = false;
  22745. this.getAlphaFromRGB = false;
  22746. this.level = 1;
  22747. this.coordinatesIndex = 0;
  22748. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  22749. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  22750. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  22751. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  22752. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  22753. this.isCube = false;
  22754. this.is3D = false;
  22755. this.gammaSpace = true;
  22756. this.invertZ = false;
  22757. this.lodLevelInAlpha = false;
  22758. this.lodGenerationOffset = 0.0;
  22759. this.lodGenerationScale = 0.8;
  22760. this.isRenderTarget = false;
  22761. this.animations = new Array();
  22762. /**
  22763. * An event triggered when the texture is disposed.
  22764. * @type {BABYLON.Observable}
  22765. */
  22766. this.onDisposeObservable = new BABYLON.Observable();
  22767. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22768. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  22769. if (this._scene) {
  22770. this._scene.textures.push(this);
  22771. }
  22772. this._uid = null;
  22773. }
  22774. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  22775. get: function () {
  22776. return this._hasAlpha;
  22777. },
  22778. set: function (value) {
  22779. if (this._hasAlpha === value) {
  22780. return;
  22781. }
  22782. this._hasAlpha = value;
  22783. if (this._scene) {
  22784. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22785. }
  22786. },
  22787. enumerable: true,
  22788. configurable: true
  22789. });
  22790. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  22791. get: function () {
  22792. return this._coordinatesMode;
  22793. },
  22794. set: function (value) {
  22795. if (this._coordinatesMode === value) {
  22796. return;
  22797. }
  22798. this._coordinatesMode = value;
  22799. if (this._scene) {
  22800. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22801. }
  22802. },
  22803. enumerable: true,
  22804. configurable: true
  22805. });
  22806. Object.defineProperty(BaseTexture.prototype, "uid", {
  22807. get: function () {
  22808. if (!this._uid) {
  22809. this._uid = BABYLON.Tools.RandomId();
  22810. }
  22811. return this._uid;
  22812. },
  22813. enumerable: true,
  22814. configurable: true
  22815. });
  22816. BaseTexture.prototype.toString = function () {
  22817. return this.name;
  22818. };
  22819. BaseTexture.prototype.getClassName = function () {
  22820. return "BaseTexture";
  22821. };
  22822. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  22823. set: function (callback) {
  22824. if (this._onDisposeObserver) {
  22825. this.onDisposeObservable.remove(this._onDisposeObserver);
  22826. }
  22827. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22828. },
  22829. enumerable: true,
  22830. configurable: true
  22831. });
  22832. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  22833. get: function () {
  22834. return true;
  22835. },
  22836. enumerable: true,
  22837. configurable: true
  22838. });
  22839. BaseTexture.prototype.getScene = function () {
  22840. return this._scene;
  22841. };
  22842. BaseTexture.prototype.getTextureMatrix = function () {
  22843. return BABYLON.Matrix.IdentityReadOnly;
  22844. };
  22845. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  22846. return BABYLON.Matrix.IdentityReadOnly;
  22847. };
  22848. BaseTexture.prototype.getInternalTexture = function () {
  22849. return this._texture;
  22850. };
  22851. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  22852. return !this.isBlocking || this.isReady();
  22853. };
  22854. BaseTexture.prototype.isReady = function () {
  22855. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22856. this.delayLoad();
  22857. return false;
  22858. }
  22859. if (this._texture) {
  22860. return this._texture.isReady;
  22861. }
  22862. return false;
  22863. };
  22864. BaseTexture.prototype.getSize = function () {
  22865. if (this._texture && this._texture.width) {
  22866. return new BABYLON.Size(this._texture.width, this._texture.height);
  22867. }
  22868. if (this._texture && this._texture._size) {
  22869. return new BABYLON.Size(this._texture._size, this._texture._size);
  22870. }
  22871. return BABYLON.Size.Zero();
  22872. };
  22873. BaseTexture.prototype.getBaseSize = function () {
  22874. if (!this.isReady() || !this._texture)
  22875. return BABYLON.Size.Zero();
  22876. if (this._texture._size) {
  22877. return new BABYLON.Size(this._texture._size, this._texture._size);
  22878. }
  22879. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  22880. };
  22881. BaseTexture.prototype.scale = function (ratio) {
  22882. };
  22883. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  22884. get: function () {
  22885. return false;
  22886. },
  22887. enumerable: true,
  22888. configurable: true
  22889. });
  22890. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  22891. if (!this._scene) {
  22892. return null;
  22893. }
  22894. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  22895. for (var index = 0; index < texturesCache.length; index++) {
  22896. var texturesCacheEntry = texturesCache[index];
  22897. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  22898. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  22899. texturesCacheEntry.incrementReferences();
  22900. return texturesCacheEntry;
  22901. }
  22902. }
  22903. }
  22904. return null;
  22905. };
  22906. BaseTexture.prototype._rebuild = function () {
  22907. };
  22908. BaseTexture.prototype.delayLoad = function () {
  22909. };
  22910. BaseTexture.prototype.clone = function () {
  22911. return null;
  22912. };
  22913. Object.defineProperty(BaseTexture.prototype, "textureType", {
  22914. get: function () {
  22915. if (!this._texture) {
  22916. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  22917. }
  22918. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  22919. },
  22920. enumerable: true,
  22921. configurable: true
  22922. });
  22923. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  22924. get: function () {
  22925. if (!this._texture) {
  22926. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  22927. }
  22928. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  22929. },
  22930. enumerable: true,
  22931. configurable: true
  22932. });
  22933. BaseTexture.prototype.readPixels = function (faceIndex) {
  22934. if (faceIndex === void 0) { faceIndex = 0; }
  22935. if (!this._texture) {
  22936. return null;
  22937. }
  22938. var size = this.getSize();
  22939. var scene = this.getScene();
  22940. if (!scene) {
  22941. return null;
  22942. }
  22943. var engine = scene.getEngine();
  22944. if (this._texture.isCube) {
  22945. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  22946. }
  22947. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  22948. };
  22949. BaseTexture.prototype.releaseInternalTexture = function () {
  22950. if (this._texture) {
  22951. this._texture.dispose();
  22952. this._texture = null;
  22953. }
  22954. };
  22955. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  22956. get: function () {
  22957. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  22958. return null;
  22959. }
  22960. if (!this._texture._sphericalPolynomial) {
  22961. this._texture._sphericalPolynomial =
  22962. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  22963. }
  22964. return this._texture._sphericalPolynomial;
  22965. },
  22966. set: function (value) {
  22967. if (this._texture) {
  22968. this._texture._sphericalPolynomial = value;
  22969. }
  22970. },
  22971. enumerable: true,
  22972. configurable: true
  22973. });
  22974. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  22975. get: function () {
  22976. if (this._texture) {
  22977. return this._texture._lodTextureHigh;
  22978. }
  22979. return null;
  22980. },
  22981. enumerable: true,
  22982. configurable: true
  22983. });
  22984. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  22985. get: function () {
  22986. if (this._texture) {
  22987. return this._texture._lodTextureMid;
  22988. }
  22989. return null;
  22990. },
  22991. enumerable: true,
  22992. configurable: true
  22993. });
  22994. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  22995. get: function () {
  22996. if (this._texture) {
  22997. return this._texture._lodTextureLow;
  22998. }
  22999. return null;
  23000. },
  23001. enumerable: true,
  23002. configurable: true
  23003. });
  23004. BaseTexture.prototype.dispose = function () {
  23005. if (!this._scene) {
  23006. return;
  23007. }
  23008. // Animations
  23009. this._scene.stopAnimation(this);
  23010. // Remove from scene
  23011. this._scene._removePendingData(this);
  23012. var index = this._scene.textures.indexOf(this);
  23013. if (index >= 0) {
  23014. this._scene.textures.splice(index, 1);
  23015. }
  23016. if (this._texture === undefined) {
  23017. return;
  23018. }
  23019. // Release
  23020. this.releaseInternalTexture();
  23021. // Callback
  23022. this.onDisposeObservable.notifyObservers(this);
  23023. this.onDisposeObservable.clear();
  23024. };
  23025. BaseTexture.prototype.serialize = function () {
  23026. if (!this.name) {
  23027. return null;
  23028. }
  23029. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23030. // Animations
  23031. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23032. return serializationObject;
  23033. };
  23034. BaseTexture.WhenAllReady = function (textures, callback) {
  23035. var numRemaining = textures.length;
  23036. if (numRemaining === 0) {
  23037. callback();
  23038. return;
  23039. }
  23040. var _loop_1 = function () {
  23041. texture = textures[i];
  23042. if (texture.isReady()) {
  23043. if (--numRemaining === 0) {
  23044. callback();
  23045. }
  23046. }
  23047. else {
  23048. onLoadObservable = texture.onLoadObservable;
  23049. var onLoadCallback_1 = function () {
  23050. onLoadObservable.removeCallback(onLoadCallback_1);
  23051. if (--numRemaining === 0) {
  23052. callback();
  23053. }
  23054. };
  23055. onLoadObservable.add(onLoadCallback_1);
  23056. }
  23057. };
  23058. var texture, onLoadObservable;
  23059. for (var i = 0; i < textures.length; i++) {
  23060. _loop_1();
  23061. }
  23062. };
  23063. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  23064. __decorate([
  23065. BABYLON.serialize()
  23066. ], BaseTexture.prototype, "name", void 0);
  23067. __decorate([
  23068. BABYLON.serialize("hasAlpha")
  23069. ], BaseTexture.prototype, "_hasAlpha", void 0);
  23070. __decorate([
  23071. BABYLON.serialize()
  23072. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  23073. __decorate([
  23074. BABYLON.serialize()
  23075. ], BaseTexture.prototype, "level", void 0);
  23076. __decorate([
  23077. BABYLON.serialize()
  23078. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  23079. __decorate([
  23080. BABYLON.serialize("coordinatesMode")
  23081. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  23082. __decorate([
  23083. BABYLON.serialize()
  23084. ], BaseTexture.prototype, "wrapU", void 0);
  23085. __decorate([
  23086. BABYLON.serialize()
  23087. ], BaseTexture.prototype, "wrapV", void 0);
  23088. __decorate([
  23089. BABYLON.serialize()
  23090. ], BaseTexture.prototype, "wrapR", void 0);
  23091. __decorate([
  23092. BABYLON.serialize()
  23093. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  23094. __decorate([
  23095. BABYLON.serialize()
  23096. ], BaseTexture.prototype, "isCube", void 0);
  23097. __decorate([
  23098. BABYLON.serialize()
  23099. ], BaseTexture.prototype, "is3D", void 0);
  23100. __decorate([
  23101. BABYLON.serialize()
  23102. ], BaseTexture.prototype, "gammaSpace", void 0);
  23103. __decorate([
  23104. BABYLON.serialize()
  23105. ], BaseTexture.prototype, "invertZ", void 0);
  23106. __decorate([
  23107. BABYLON.serialize()
  23108. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  23109. __decorate([
  23110. BABYLON.serialize()
  23111. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  23112. __decorate([
  23113. BABYLON.serialize()
  23114. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  23115. __decorate([
  23116. BABYLON.serialize()
  23117. ], BaseTexture.prototype, "isRenderTarget", void 0);
  23118. return BaseTexture;
  23119. }());
  23120. BABYLON.BaseTexture = BaseTexture;
  23121. })(BABYLON || (BABYLON = {}));
  23122. //# sourceMappingURL=babylon.baseTexture.js.map
  23123. var BABYLON;
  23124. (function (BABYLON) {
  23125. var Texture = /** @class */ (function (_super) {
  23126. __extends(Texture, _super);
  23127. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  23128. if (noMipmap === void 0) { noMipmap = false; }
  23129. if (invertY === void 0) { invertY = true; }
  23130. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  23131. if (onLoad === void 0) { onLoad = null; }
  23132. if (onError === void 0) { onError = null; }
  23133. if (buffer === void 0) { buffer = null; }
  23134. if (deleteBuffer === void 0) { deleteBuffer = false; }
  23135. var _this = _super.call(this, scene) || this;
  23136. _this.uOffset = 0;
  23137. _this.vOffset = 0;
  23138. _this.uScale = 1.0;
  23139. _this.vScale = 1.0;
  23140. _this.uAng = 0;
  23141. _this.vAng = 0;
  23142. _this.wAng = 0;
  23143. _this._isBlocking = true;
  23144. _this.name = url || "";
  23145. _this.url = url;
  23146. _this._noMipmap = noMipmap;
  23147. _this._invertY = invertY;
  23148. _this._samplingMode = samplingMode;
  23149. _this._buffer = buffer;
  23150. _this._deleteBuffer = deleteBuffer;
  23151. if (format) {
  23152. _this._format = format;
  23153. }
  23154. scene = _this.getScene();
  23155. if (!scene) {
  23156. return _this;
  23157. }
  23158. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  23159. var load = function () {
  23160. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  23161. _this.onLoadObservable.notifyObservers(_this);
  23162. }
  23163. if (onLoad) {
  23164. onLoad();
  23165. }
  23166. if (!_this.isBlocking && scene) {
  23167. scene.resetCachedMaterial();
  23168. }
  23169. };
  23170. if (!_this.url) {
  23171. _this._delayedOnLoad = load;
  23172. _this._delayedOnError = onError;
  23173. return _this;
  23174. }
  23175. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  23176. if (!_this._texture) {
  23177. if (!scene.useDelayedTextureLoading) {
  23178. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  23179. if (deleteBuffer) {
  23180. delete _this._buffer;
  23181. }
  23182. }
  23183. else {
  23184. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  23185. _this._delayedOnLoad = load;
  23186. _this._delayedOnError = onError;
  23187. }
  23188. }
  23189. else {
  23190. if (_this._texture.isReady) {
  23191. BABYLON.Tools.SetImmediate(function () { return load(); });
  23192. }
  23193. else {
  23194. _this._texture.onLoadedObservable.add(load);
  23195. }
  23196. }
  23197. return _this;
  23198. }
  23199. Object.defineProperty(Texture.prototype, "noMipmap", {
  23200. get: function () {
  23201. return this._noMipmap;
  23202. },
  23203. enumerable: true,
  23204. configurable: true
  23205. });
  23206. Object.defineProperty(Texture.prototype, "isBlocking", {
  23207. get: function () {
  23208. return this._isBlocking;
  23209. },
  23210. set: function (value) {
  23211. this._isBlocking = value;
  23212. },
  23213. enumerable: true,
  23214. configurable: true
  23215. });
  23216. Object.defineProperty(Texture.prototype, "samplingMode", {
  23217. get: function () {
  23218. return this._samplingMode;
  23219. },
  23220. enumerable: true,
  23221. configurable: true
  23222. });
  23223. Texture.prototype.updateURL = function (url) {
  23224. this.url = url;
  23225. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  23226. this.delayLoad();
  23227. };
  23228. Texture.prototype.delayLoad = function () {
  23229. var _this = this;
  23230. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23231. return;
  23232. }
  23233. var scene = this.getScene();
  23234. if (!scene) {
  23235. return;
  23236. }
  23237. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23238. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  23239. if (!this._texture) {
  23240. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  23241. if (this._deleteBuffer) {
  23242. delete this._buffer;
  23243. }
  23244. }
  23245. else {
  23246. if (this._texture.isReady) {
  23247. BABYLON.Tools.SetImmediate(function () {
  23248. if (!_this._delayedOnLoad) {
  23249. return;
  23250. }
  23251. _this._delayedOnLoad();
  23252. });
  23253. }
  23254. else {
  23255. if (this._delayedOnLoad) {
  23256. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  23257. }
  23258. }
  23259. }
  23260. };
  23261. Texture.prototype.updateSamplingMode = function (samplingMode) {
  23262. if (!this._texture) {
  23263. return;
  23264. }
  23265. var scene = this.getScene();
  23266. if (!scene) {
  23267. return;
  23268. }
  23269. this._samplingMode = samplingMode;
  23270. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  23271. };
  23272. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  23273. x *= this.uScale;
  23274. y *= this.vScale;
  23275. x -= 0.5 * this.uScale;
  23276. y -= 0.5 * this.vScale;
  23277. z -= 0.5;
  23278. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  23279. t.x += 0.5 * this.uScale + this.uOffset;
  23280. t.y += 0.5 * this.vScale + this.vOffset;
  23281. t.z += 0.5;
  23282. };
  23283. Texture.prototype.getTextureMatrix = function () {
  23284. var _this = this;
  23285. if (this.uOffset === this._cachedUOffset &&
  23286. this.vOffset === this._cachedVOffset &&
  23287. this.uScale === this._cachedUScale &&
  23288. this.vScale === this._cachedVScale &&
  23289. this.uAng === this._cachedUAng &&
  23290. this.vAng === this._cachedVAng &&
  23291. this.wAng === this._cachedWAng) {
  23292. return this._cachedTextureMatrix;
  23293. }
  23294. this._cachedUOffset = this.uOffset;
  23295. this._cachedVOffset = this.vOffset;
  23296. this._cachedUScale = this.uScale;
  23297. this._cachedVScale = this.vScale;
  23298. this._cachedUAng = this.uAng;
  23299. this._cachedVAng = this.vAng;
  23300. this._cachedWAng = this.wAng;
  23301. if (!this._cachedTextureMatrix) {
  23302. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  23303. this._rowGenerationMatrix = new BABYLON.Matrix();
  23304. this._t0 = BABYLON.Vector3.Zero();
  23305. this._t1 = BABYLON.Vector3.Zero();
  23306. this._t2 = BABYLON.Vector3.Zero();
  23307. }
  23308. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  23309. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  23310. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  23311. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  23312. this._t1.subtractInPlace(this._t0);
  23313. this._t2.subtractInPlace(this._t0);
  23314. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  23315. this._cachedTextureMatrix.m[0] = this._t1.x;
  23316. this._cachedTextureMatrix.m[1] = this._t1.y;
  23317. this._cachedTextureMatrix.m[2] = this._t1.z;
  23318. this._cachedTextureMatrix.m[4] = this._t2.x;
  23319. this._cachedTextureMatrix.m[5] = this._t2.y;
  23320. this._cachedTextureMatrix.m[6] = this._t2.z;
  23321. this._cachedTextureMatrix.m[8] = this._t0.x;
  23322. this._cachedTextureMatrix.m[9] = this._t0.y;
  23323. this._cachedTextureMatrix.m[10] = this._t0.z;
  23324. var scene = this.getScene();
  23325. if (!scene) {
  23326. return this._cachedTextureMatrix;
  23327. }
  23328. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  23329. return mat.hasTexture(_this);
  23330. });
  23331. return this._cachedTextureMatrix;
  23332. };
  23333. Texture.prototype.getReflectionTextureMatrix = function () {
  23334. var _this = this;
  23335. var scene = this.getScene();
  23336. if (!scene) {
  23337. return this._cachedTextureMatrix;
  23338. }
  23339. if (this.uOffset === this._cachedUOffset &&
  23340. this.vOffset === this._cachedVOffset &&
  23341. this.uScale === this._cachedUScale &&
  23342. this.vScale === this._cachedVScale &&
  23343. this.coordinatesMode === this._cachedCoordinatesMode) {
  23344. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  23345. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  23346. return this._cachedTextureMatrix;
  23347. }
  23348. }
  23349. else {
  23350. return this._cachedTextureMatrix;
  23351. }
  23352. }
  23353. if (!this._cachedTextureMatrix) {
  23354. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  23355. }
  23356. if (!this._projectionModeMatrix) {
  23357. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  23358. }
  23359. this._cachedUOffset = this.uOffset;
  23360. this._cachedVOffset = this.vOffset;
  23361. this._cachedUScale = this.uScale;
  23362. this._cachedVScale = this.vScale;
  23363. this._cachedCoordinatesMode = this.coordinatesMode;
  23364. switch (this.coordinatesMode) {
  23365. case Texture.PLANAR_MODE:
  23366. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  23367. this._cachedTextureMatrix[0] = this.uScale;
  23368. this._cachedTextureMatrix[5] = this.vScale;
  23369. this._cachedTextureMatrix[12] = this.uOffset;
  23370. this._cachedTextureMatrix[13] = this.vOffset;
  23371. break;
  23372. case Texture.PROJECTION_MODE:
  23373. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  23374. this._projectionModeMatrix.m[0] = 0.5;
  23375. this._projectionModeMatrix.m[5] = -0.5;
  23376. this._projectionModeMatrix.m[10] = 0.0;
  23377. this._projectionModeMatrix.m[12] = 0.5;
  23378. this._projectionModeMatrix.m[13] = 0.5;
  23379. this._projectionModeMatrix.m[14] = 1.0;
  23380. this._projectionModeMatrix.m[15] = 1.0;
  23381. var projectionMatrix = scene.getProjectionMatrix();
  23382. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  23383. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  23384. break;
  23385. default:
  23386. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  23387. break;
  23388. }
  23389. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  23390. return (mat.getActiveTextures().indexOf(_this) !== -1);
  23391. });
  23392. return this._cachedTextureMatrix;
  23393. };
  23394. Texture.prototype.clone = function () {
  23395. var _this = this;
  23396. return BABYLON.SerializationHelper.Clone(function () {
  23397. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  23398. }, this);
  23399. };
  23400. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  23401. get: function () {
  23402. if (!this._onLoadObservable) {
  23403. this._onLoadObservable = new BABYLON.Observable();
  23404. }
  23405. return this._onLoadObservable;
  23406. },
  23407. enumerable: true,
  23408. configurable: true
  23409. });
  23410. Texture.prototype.serialize = function () {
  23411. var serializationObject = _super.prototype.serialize.call(this);
  23412. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  23413. serializationObject.base64String = this._buffer;
  23414. serializationObject.name = serializationObject.name.replace("data:", "");
  23415. }
  23416. return serializationObject;
  23417. };
  23418. Texture.prototype.getClassName = function () {
  23419. return "Texture";
  23420. };
  23421. Texture.prototype.dispose = function () {
  23422. _super.prototype.dispose.call(this);
  23423. if (this.onLoadObservable) {
  23424. this.onLoadObservable.clear();
  23425. this._onLoadObservable = null;
  23426. }
  23427. this._delayedOnLoad = null;
  23428. this._delayedOnError = null;
  23429. };
  23430. // Statics
  23431. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  23432. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  23433. if (onLoad === void 0) { onLoad = null; }
  23434. if (onError === void 0) { onError = null; }
  23435. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  23436. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  23437. };
  23438. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  23439. if (parsedTexture.customType) {
  23440. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  23441. // Update Sampling Mode
  23442. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  23443. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  23444. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  23445. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  23446. }
  23447. }
  23448. return parsedCustomTexture;
  23449. }
  23450. if (parsedTexture.isCube) {
  23451. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  23452. }
  23453. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  23454. return null;
  23455. }
  23456. var texture = BABYLON.SerializationHelper.Parse(function () {
  23457. var generateMipMaps = true;
  23458. if (parsedTexture.noMipmap) {
  23459. generateMipMaps = false;
  23460. }
  23461. if (parsedTexture.mirrorPlane) {
  23462. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  23463. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  23464. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  23465. return mirrorTexture;
  23466. }
  23467. else if (parsedTexture.isRenderTarget) {
  23468. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  23469. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  23470. return renderTargetTexture;
  23471. }
  23472. else {
  23473. var texture;
  23474. if (parsedTexture.base64String) {
  23475. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  23476. }
  23477. else {
  23478. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  23479. }
  23480. return texture;
  23481. }
  23482. }, parsedTexture, scene);
  23483. // Update Sampling Mode
  23484. if (parsedTexture.samplingMode) {
  23485. var sampling = parsedTexture.samplingMode;
  23486. if (texture._samplingMode !== sampling) {
  23487. texture.updateSamplingMode(sampling);
  23488. }
  23489. }
  23490. // Animations
  23491. if (parsedTexture.animations) {
  23492. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  23493. var parsedAnimation = parsedTexture.animations[animationIndex];
  23494. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23495. }
  23496. }
  23497. return texture;
  23498. };
  23499. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  23500. if (deleteBuffer === void 0) { deleteBuffer = false; }
  23501. if (noMipmap === void 0) { noMipmap = false; }
  23502. if (invertY === void 0) { invertY = true; }
  23503. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  23504. if (onLoad === void 0) { onLoad = null; }
  23505. if (onError === void 0) { onError = null; }
  23506. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  23507. if (name.substr(0, 5) !== "data:") {
  23508. name = "data:" + name;
  23509. }
  23510. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  23511. };
  23512. // Constants
  23513. Texture.NEAREST_SAMPLINGMODE = 1;
  23514. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  23515. Texture.BILINEAR_SAMPLINGMODE = 2;
  23516. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  23517. Texture.TRILINEAR_SAMPLINGMODE = 3;
  23518. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  23519. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  23520. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  23521. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  23522. Texture.NEAREST_LINEAR = 7;
  23523. Texture.NEAREST_NEAREST = 8;
  23524. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  23525. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  23526. Texture.LINEAR_LINEAR = 11;
  23527. Texture.LINEAR_NEAREST = 12;
  23528. Texture.EXPLICIT_MODE = 0;
  23529. Texture.SPHERICAL_MODE = 1;
  23530. Texture.PLANAR_MODE = 2;
  23531. Texture.CUBIC_MODE = 3;
  23532. Texture.PROJECTION_MODE = 4;
  23533. Texture.SKYBOX_MODE = 5;
  23534. Texture.INVCUBIC_MODE = 6;
  23535. Texture.EQUIRECTANGULAR_MODE = 7;
  23536. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  23537. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  23538. Texture.CLAMP_ADDRESSMODE = 0;
  23539. Texture.WRAP_ADDRESSMODE = 1;
  23540. Texture.MIRROR_ADDRESSMODE = 2;
  23541. __decorate([
  23542. BABYLON.serialize()
  23543. ], Texture.prototype, "url", void 0);
  23544. __decorate([
  23545. BABYLON.serialize()
  23546. ], Texture.prototype, "uOffset", void 0);
  23547. __decorate([
  23548. BABYLON.serialize()
  23549. ], Texture.prototype, "vOffset", void 0);
  23550. __decorate([
  23551. BABYLON.serialize()
  23552. ], Texture.prototype, "uScale", void 0);
  23553. __decorate([
  23554. BABYLON.serialize()
  23555. ], Texture.prototype, "vScale", void 0);
  23556. __decorate([
  23557. BABYLON.serialize()
  23558. ], Texture.prototype, "uAng", void 0);
  23559. __decorate([
  23560. BABYLON.serialize()
  23561. ], Texture.prototype, "vAng", void 0);
  23562. __decorate([
  23563. BABYLON.serialize()
  23564. ], Texture.prototype, "wAng", void 0);
  23565. __decorate([
  23566. BABYLON.serialize()
  23567. ], Texture.prototype, "isBlocking", null);
  23568. return Texture;
  23569. }(BABYLON.BaseTexture));
  23570. BABYLON.Texture = Texture;
  23571. })(BABYLON || (BABYLON = {}));
  23572. //# sourceMappingURL=babylon.texture.js.map
  23573. var BABYLON;
  23574. (function (BABYLON) {
  23575. var _InstancesBatch = /** @class */ (function () {
  23576. function _InstancesBatch() {
  23577. this.mustReturn = false;
  23578. this.visibleInstances = new Array();
  23579. this.renderSelf = new Array();
  23580. }
  23581. return _InstancesBatch;
  23582. }());
  23583. BABYLON._InstancesBatch = _InstancesBatch;
  23584. var Mesh = /** @class */ (function (_super) {
  23585. __extends(Mesh, _super);
  23586. /**
  23587. * @constructor
  23588. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  23589. * @param {Scene} scene The scene to add this mesh to.
  23590. * @param {Node} parent The parent of this mesh, if it has one
  23591. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  23592. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  23593. * When false, achieved by calling a clone(), also passing False.
  23594. * This will make creation of children, recursive.
  23595. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  23596. */
  23597. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  23598. if (scene === void 0) { scene = null; }
  23599. if (parent === void 0) { parent = null; }
  23600. if (source === void 0) { source = null; }
  23601. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  23602. var _this = _super.call(this, name, scene) || this;
  23603. // Events
  23604. /**
  23605. * An event triggered before rendering the mesh
  23606. * @type {BABYLON.Observable}
  23607. */
  23608. _this.onBeforeRenderObservable = new BABYLON.Observable();
  23609. /**
  23610. * An event triggered after rendering the mesh
  23611. * @type {BABYLON.Observable}
  23612. */
  23613. _this.onAfterRenderObservable = new BABYLON.Observable();
  23614. /**
  23615. * An event triggered before drawing the mesh
  23616. * @type {BABYLON.Observable}
  23617. */
  23618. _this.onBeforeDrawObservable = new BABYLON.Observable();
  23619. // Members
  23620. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23621. _this.instances = new Array();
  23622. _this._LODLevels = new Array();
  23623. _this._visibleInstances = {};
  23624. _this._renderIdForInstances = new Array();
  23625. _this._batchCache = new _InstancesBatch();
  23626. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  23627. // Use by builder only to know what orientation were the mesh build in.
  23628. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  23629. _this.overrideMaterialSideOrientation = null;
  23630. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  23631. // Will be used to save a source mesh reference, If any
  23632. _this._source = null;
  23633. scene = _this.getScene();
  23634. if (source) {
  23635. // Source mesh
  23636. _this._source = source;
  23637. // Geometry
  23638. if (source._geometry) {
  23639. source._geometry.applyToMesh(_this);
  23640. }
  23641. // Deep copy
  23642. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source"], ["_poseMatrix", "_source"]);
  23643. // Tags
  23644. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  23645. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  23646. }
  23647. _this.metadata = source.metadata;
  23648. // Parent
  23649. _this.parent = source.parent;
  23650. // Pivot
  23651. _this.setPivotMatrix(source.getPivotMatrix());
  23652. _this.id = name + "." + source.id;
  23653. // Material
  23654. _this.material = source.material;
  23655. var index;
  23656. if (!doNotCloneChildren) {
  23657. // Children
  23658. var directDescendants = source.getDescendants(true);
  23659. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  23660. var child = directDescendants[index_1];
  23661. if (child.clone) {
  23662. child.clone(name + "." + child.name, _this);
  23663. }
  23664. }
  23665. }
  23666. // Physics clone
  23667. var physicsEngine = _this.getScene().getPhysicsEngine();
  23668. if (clonePhysicsImpostor && physicsEngine) {
  23669. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  23670. if (impostor) {
  23671. _this.physicsImpostor = impostor.clone(_this);
  23672. }
  23673. }
  23674. // Particles
  23675. for (index = 0; index < scene.particleSystems.length; index++) {
  23676. var system = scene.particleSystems[index];
  23677. if (system.emitter === source) {
  23678. system.clone(system.name, _this);
  23679. }
  23680. }
  23681. _this.computeWorldMatrix(true);
  23682. }
  23683. // Parent
  23684. if (parent !== null) {
  23685. _this.parent = parent;
  23686. }
  23687. return _this;
  23688. }
  23689. Object.defineProperty(Mesh, "FRONTSIDE", {
  23690. /**
  23691. * Mesh side orientation : usually the external or front surface
  23692. */
  23693. get: function () {
  23694. return Mesh._FRONTSIDE;
  23695. },
  23696. enumerable: true,
  23697. configurable: true
  23698. });
  23699. Object.defineProperty(Mesh, "BACKSIDE", {
  23700. /**
  23701. * Mesh side orientation : usually the internal or back surface
  23702. */
  23703. get: function () {
  23704. return Mesh._BACKSIDE;
  23705. },
  23706. enumerable: true,
  23707. configurable: true
  23708. });
  23709. Object.defineProperty(Mesh, "DOUBLESIDE", {
  23710. /**
  23711. * Mesh side orientation : both internal and external or front and back surfaces
  23712. */
  23713. get: function () {
  23714. return Mesh._DOUBLESIDE;
  23715. },
  23716. enumerable: true,
  23717. configurable: true
  23718. });
  23719. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  23720. /**
  23721. * Mesh side orientation : by default, `FRONTSIDE`
  23722. */
  23723. get: function () {
  23724. return Mesh._DEFAULTSIDE;
  23725. },
  23726. enumerable: true,
  23727. configurable: true
  23728. });
  23729. Object.defineProperty(Mesh, "NO_CAP", {
  23730. /**
  23731. * Mesh cap setting : no cap
  23732. */
  23733. get: function () {
  23734. return Mesh._NO_CAP;
  23735. },
  23736. enumerable: true,
  23737. configurable: true
  23738. });
  23739. Object.defineProperty(Mesh, "CAP_START", {
  23740. /**
  23741. * Mesh cap setting : one cap at the beginning of the mesh
  23742. */
  23743. get: function () {
  23744. return Mesh._CAP_START;
  23745. },
  23746. enumerable: true,
  23747. configurable: true
  23748. });
  23749. Object.defineProperty(Mesh, "CAP_END", {
  23750. /**
  23751. * Mesh cap setting : one cap at the end of the mesh
  23752. */
  23753. get: function () {
  23754. return Mesh._CAP_END;
  23755. },
  23756. enumerable: true,
  23757. configurable: true
  23758. });
  23759. Object.defineProperty(Mesh, "CAP_ALL", {
  23760. /**
  23761. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  23762. */
  23763. get: function () {
  23764. return Mesh._CAP_ALL;
  23765. },
  23766. enumerable: true,
  23767. configurable: true
  23768. });
  23769. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  23770. set: function (callback) {
  23771. if (this._onBeforeDrawObserver) {
  23772. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  23773. }
  23774. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  23775. },
  23776. enumerable: true,
  23777. configurable: true
  23778. });
  23779. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  23780. get: function () {
  23781. return this._morphTargetManager;
  23782. },
  23783. set: function (value) {
  23784. if (this._morphTargetManager === value) {
  23785. return;
  23786. }
  23787. this._morphTargetManager = value;
  23788. this._syncGeometryWithMorphTargetManager();
  23789. },
  23790. enumerable: true,
  23791. configurable: true
  23792. });
  23793. Object.defineProperty(Mesh.prototype, "source", {
  23794. get: function () {
  23795. return this._source;
  23796. },
  23797. enumerable: true,
  23798. configurable: true
  23799. });
  23800. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  23801. get: function () {
  23802. return this._unIndexed;
  23803. },
  23804. set: function (value) {
  23805. if (this._unIndexed !== value) {
  23806. this._unIndexed = value;
  23807. this._markSubMeshesAsAttributesDirty();
  23808. }
  23809. },
  23810. enumerable: true,
  23811. configurable: true
  23812. });
  23813. // Methods
  23814. /**
  23815. * Returns the string "Mesh".
  23816. */
  23817. Mesh.prototype.getClassName = function () {
  23818. return "Mesh";
  23819. };
  23820. /**
  23821. * Returns a string.
  23822. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  23823. */
  23824. Mesh.prototype.toString = function (fullDetails) {
  23825. var ret = _super.prototype.toString.call(this, fullDetails);
  23826. ret += ", n vertices: " + this.getTotalVertices();
  23827. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  23828. if (this.animations) {
  23829. for (var i = 0; i < this.animations.length; i++) {
  23830. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  23831. }
  23832. }
  23833. if (fullDetails) {
  23834. if (this._geometry) {
  23835. var ib = this.getIndices();
  23836. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23837. if (vb && ib) {
  23838. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  23839. }
  23840. }
  23841. else {
  23842. ret += ", flat shading: UNKNOWN";
  23843. }
  23844. }
  23845. return ret;
  23846. };
  23847. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  23848. /**
  23849. * True if the mesh has some Levels Of Details (LOD).
  23850. * Returns a boolean.
  23851. */
  23852. get: function () {
  23853. return this._LODLevels.length > 0;
  23854. },
  23855. enumerable: true,
  23856. configurable: true
  23857. });
  23858. Mesh.prototype._sortLODLevels = function () {
  23859. this._LODLevels.sort(function (a, b) {
  23860. if (a.distance < b.distance) {
  23861. return 1;
  23862. }
  23863. if (a.distance > b.distance) {
  23864. return -1;
  23865. }
  23866. return 0;
  23867. });
  23868. };
  23869. /**
  23870. * Add a mesh as LOD level triggered at the given distance.
  23871. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23872. * @param {number} distance The distance from the center of the object to show this level
  23873. * @param {Mesh} mesh The mesh to be added as LOD level
  23874. * @return {Mesh} This mesh (for chaining)
  23875. */
  23876. Mesh.prototype.addLODLevel = function (distance, mesh) {
  23877. if (mesh && mesh._masterMesh) {
  23878. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  23879. return this;
  23880. }
  23881. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  23882. this._LODLevels.push(level);
  23883. if (mesh) {
  23884. mesh._masterMesh = this;
  23885. }
  23886. this._sortLODLevels();
  23887. return this;
  23888. };
  23889. /**
  23890. * Returns the LOD level mesh at the passed distance or null if not found.
  23891. * It is related to the method `addLODLevel(distance, mesh)`.
  23892. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23893. * Returns an object Mesh or `null`.
  23894. */
  23895. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  23896. for (var index = 0; index < this._LODLevels.length; index++) {
  23897. var level = this._LODLevels[index];
  23898. if (level.distance === distance) {
  23899. return level.mesh;
  23900. }
  23901. }
  23902. return null;
  23903. };
  23904. /**
  23905. * Remove a mesh from the LOD array
  23906. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23907. * @param {Mesh} mesh The mesh to be removed.
  23908. * @return {Mesh} This mesh (for chaining)
  23909. */
  23910. Mesh.prototype.removeLODLevel = function (mesh) {
  23911. for (var index = 0; index < this._LODLevels.length; index++) {
  23912. if (this._LODLevels[index].mesh === mesh) {
  23913. this._LODLevels.splice(index, 1);
  23914. if (mesh) {
  23915. mesh._masterMesh = null;
  23916. }
  23917. }
  23918. }
  23919. this._sortLODLevels();
  23920. return this;
  23921. };
  23922. /**
  23923. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  23924. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23925. */
  23926. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  23927. if (!this._LODLevels || this._LODLevels.length === 0) {
  23928. return this;
  23929. }
  23930. var bSphere;
  23931. if (boundingSphere) {
  23932. bSphere = boundingSphere;
  23933. }
  23934. else {
  23935. var boundingInfo = this.getBoundingInfo();
  23936. bSphere = boundingInfo.boundingSphere;
  23937. }
  23938. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  23939. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  23940. if (this.onLODLevelSelection) {
  23941. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  23942. }
  23943. return this;
  23944. }
  23945. for (var index = 0; index < this._LODLevels.length; index++) {
  23946. var level = this._LODLevels[index];
  23947. if (level.distance < distanceToCamera) {
  23948. if (level.mesh) {
  23949. level.mesh._preActivate();
  23950. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  23951. }
  23952. if (this.onLODLevelSelection) {
  23953. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  23954. }
  23955. return level.mesh;
  23956. }
  23957. }
  23958. if (this.onLODLevelSelection) {
  23959. this.onLODLevelSelection(distanceToCamera, this, this);
  23960. }
  23961. return this;
  23962. };
  23963. Object.defineProperty(Mesh.prototype, "geometry", {
  23964. /**
  23965. * Returns the mesh internal Geometry object.
  23966. */
  23967. get: function () {
  23968. return this._geometry;
  23969. },
  23970. enumerable: true,
  23971. configurable: true
  23972. });
  23973. /**
  23974. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  23975. */
  23976. Mesh.prototype.getTotalVertices = function () {
  23977. if (this._geometry === null || this._geometry === undefined) {
  23978. return 0;
  23979. }
  23980. return this._geometry.getTotalVertices();
  23981. };
  23982. /**
  23983. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  23984. * 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.
  23985. * You can force the copy with forceCopy === true
  23986. * Returns null if the mesh has no geometry or no vertex buffer.
  23987. * Possible `kind` values :
  23988. * - BABYLON.VertexBuffer.PositionKind
  23989. * - BABYLON.VertexBuffer.UVKind
  23990. * - BABYLON.VertexBuffer.UV2Kind
  23991. * - BABYLON.VertexBuffer.UV3Kind
  23992. * - BABYLON.VertexBuffer.UV4Kind
  23993. * - BABYLON.VertexBuffer.UV5Kind
  23994. * - BABYLON.VertexBuffer.UV6Kind
  23995. * - BABYLON.VertexBuffer.ColorKind
  23996. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23997. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23998. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23999. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  24000. */
  24001. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  24002. if (!this._geometry) {
  24003. return null;
  24004. }
  24005. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  24006. };
  24007. /**
  24008. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  24009. * Returns `null` if the mesh has no geometry.
  24010. * Possible `kind` values :
  24011. * - BABYLON.VertexBuffer.PositionKind
  24012. * - BABYLON.VertexBuffer.UVKind
  24013. * - BABYLON.VertexBuffer.UV2Kind
  24014. * - BABYLON.VertexBuffer.UV3Kind
  24015. * - BABYLON.VertexBuffer.UV4Kind
  24016. * - BABYLON.VertexBuffer.UV5Kind
  24017. * - BABYLON.VertexBuffer.UV6Kind
  24018. * - BABYLON.VertexBuffer.ColorKind
  24019. * - BABYLON.VertexBuffer.MatricesIndicesKind
  24020. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  24021. * - BABYLON.VertexBuffer.MatricesWeightsKind
  24022. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  24023. */
  24024. Mesh.prototype.getVertexBuffer = function (kind) {
  24025. if (!this._geometry) {
  24026. return null;
  24027. }
  24028. return this._geometry.getVertexBuffer(kind);
  24029. };
  24030. /**
  24031. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  24032. * Possible `kind` values :
  24033. * - BABYLON.VertexBuffer.PositionKind
  24034. * - BABYLON.VertexBuffer.UVKind
  24035. * - BABYLON.VertexBuffer.UV2Kind
  24036. * - BABYLON.VertexBuffer.UV3Kind
  24037. * - BABYLON.VertexBuffer.UV4Kind
  24038. * - BABYLON.VertexBuffer.UV5Kind
  24039. * - BABYLON.VertexBuffer.UV6Kind
  24040. * - BABYLON.VertexBuffer.ColorKind
  24041. * - BABYLON.VertexBuffer.MatricesIndicesKind
  24042. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  24043. * - BABYLON.VertexBuffer.MatricesWeightsKind
  24044. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  24045. */
  24046. Mesh.prototype.isVerticesDataPresent = function (kind) {
  24047. if (!this._geometry) {
  24048. if (this._delayInfo) {
  24049. return this._delayInfo.indexOf(kind) !== -1;
  24050. }
  24051. return false;
  24052. }
  24053. return this._geometry.isVerticesDataPresent(kind);
  24054. };
  24055. /**
  24056. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  24057. * Possible `kind` values :
  24058. * - BABYLON.VertexBuffer.PositionKind
  24059. * - BABYLON.VertexBuffer.UVKind
  24060. * - BABYLON.VertexBuffer.UV2Kind
  24061. * - BABYLON.VertexBuffer.UV3Kind
  24062. * - BABYLON.VertexBuffer.UV4Kind
  24063. * - BABYLON.VertexBuffer.UV5Kind
  24064. * - BABYLON.VertexBuffer.UV6Kind
  24065. * - BABYLON.VertexBuffer.ColorKind
  24066. * - BABYLON.VertexBuffer.MatricesIndicesKind
  24067. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  24068. * - BABYLON.VertexBuffer.MatricesWeightsKind
  24069. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  24070. */
  24071. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  24072. if (!this._geometry) {
  24073. if (this._delayInfo) {
  24074. return this._delayInfo.indexOf(kind) !== -1;
  24075. }
  24076. return false;
  24077. }
  24078. return this._geometry.isVertexBufferUpdatable(kind);
  24079. };
  24080. /**
  24081. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  24082. * Possible `kind` values :
  24083. * - BABYLON.VertexBuffer.PositionKind
  24084. * - BABYLON.VertexBuffer.UVKind
  24085. * - BABYLON.VertexBuffer.UV2Kind
  24086. * - BABYLON.VertexBuffer.UV3Kind
  24087. * - BABYLON.VertexBuffer.UV4Kind
  24088. * - BABYLON.VertexBuffer.UV5Kind
  24089. * - BABYLON.VertexBuffer.UV6Kind
  24090. * - BABYLON.VertexBuffer.ColorKind
  24091. * - BABYLON.VertexBuffer.MatricesIndicesKind
  24092. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  24093. * - BABYLON.VertexBuffer.MatricesWeightsKind
  24094. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  24095. */
  24096. Mesh.prototype.getVerticesDataKinds = function () {
  24097. if (!this._geometry) {
  24098. var result = new Array();
  24099. if (this._delayInfo) {
  24100. this._delayInfo.forEach(function (kind, index, array) {
  24101. result.push(kind);
  24102. });
  24103. }
  24104. return result;
  24105. }
  24106. return this._geometry.getVerticesDataKinds();
  24107. };
  24108. /**
  24109. * Returns a positive integer : the total number of indices in this mesh geometry.
  24110. * Returns zero if the mesh has no geometry.
  24111. */
  24112. Mesh.prototype.getTotalIndices = function () {
  24113. if (!this._geometry) {
  24114. return 0;
  24115. }
  24116. return this._geometry.getTotalIndices();
  24117. };
  24118. /**
  24119. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  24120. * 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.
  24121. * Returns an empty array if the mesh has no geometry.
  24122. */
  24123. Mesh.prototype.getIndices = function (copyWhenShared) {
  24124. if (!this._geometry) {
  24125. return [];
  24126. }
  24127. return this._geometry.getIndices(copyWhenShared);
  24128. };
  24129. Object.defineProperty(Mesh.prototype, "isBlocked", {
  24130. get: function () {
  24131. return this._masterMesh !== null && this._masterMesh !== undefined;
  24132. },
  24133. enumerable: true,
  24134. configurable: true
  24135. });
  24136. /**
  24137. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  24138. */
  24139. Mesh.prototype.isReady = function () {
  24140. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  24141. return false;
  24142. }
  24143. return _super.prototype.isReady.call(this);
  24144. };
  24145. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  24146. /**
  24147. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  24148. * This property is pertinent only for updatable parametric shapes.
  24149. */
  24150. get: function () {
  24151. return this._areNormalsFrozen;
  24152. },
  24153. enumerable: true,
  24154. configurable: true
  24155. });
  24156. /**
  24157. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  24158. * It has no effect at all on other shapes.
  24159. * It prevents the mesh normals from being recomputed on next `positions` array update.
  24160. * Returns the Mesh.
  24161. */
  24162. Mesh.prototype.freezeNormals = function () {
  24163. this._areNormalsFrozen = true;
  24164. return this;
  24165. };
  24166. /**
  24167. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  24168. * It has no effect at all on other shapes.
  24169. * It reactivates the mesh normals computation if it was previously frozen.
  24170. * Returns the Mesh.
  24171. */
  24172. Mesh.prototype.unfreezeNormals = function () {
  24173. this._areNormalsFrozen = false;
  24174. return this;
  24175. };
  24176. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  24177. /**
  24178. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  24179. */
  24180. set: function (count) {
  24181. this._overridenInstanceCount = count;
  24182. },
  24183. enumerable: true,
  24184. configurable: true
  24185. });
  24186. // Methods
  24187. Mesh.prototype._preActivate = function () {
  24188. var sceneRenderId = this.getScene().getRenderId();
  24189. if (this._preActivateId === sceneRenderId) {
  24190. return this;
  24191. }
  24192. this._preActivateId = sceneRenderId;
  24193. this._visibleInstances = null;
  24194. return this;
  24195. };
  24196. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  24197. if (this._visibleInstances) {
  24198. this._visibleInstances.intermediateDefaultRenderId = renderId;
  24199. }
  24200. return this;
  24201. };
  24202. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  24203. if (!this._visibleInstances) {
  24204. this._visibleInstances = {};
  24205. this._visibleInstances.defaultRenderId = renderId;
  24206. this._visibleInstances.selfDefaultRenderId = this._renderId;
  24207. }
  24208. if (!this._visibleInstances[renderId]) {
  24209. this._visibleInstances[renderId] = new Array();
  24210. }
  24211. this._visibleInstances[renderId].push(instance);
  24212. return this;
  24213. };
  24214. /**
  24215. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  24216. * This means the mesh underlying bounding box and sphere are recomputed.
  24217. * Returns the Mesh.
  24218. */
  24219. Mesh.prototype.refreshBoundingInfo = function () {
  24220. return this._refreshBoundingInfo(false);
  24221. };
  24222. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  24223. if (this._boundingInfo && this._boundingInfo.isLocked) {
  24224. return this;
  24225. }
  24226. var data = this._getPositionData(applySkeleton);
  24227. if (data) {
  24228. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  24229. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24230. }
  24231. if (this.subMeshes) {
  24232. for (var index = 0; index < this.subMeshes.length; index++) {
  24233. this.subMeshes[index].refreshBoundingInfo();
  24234. }
  24235. }
  24236. this._updateBoundingInfo();
  24237. return this;
  24238. };
  24239. Mesh.prototype._getPositionData = function (applySkeleton) {
  24240. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24241. if (data && applySkeleton && this.skeleton) {
  24242. data = data.slice();
  24243. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  24244. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  24245. if (matricesWeightsData && matricesIndicesData) {
  24246. var needExtras = this.numBoneInfluencers > 4;
  24247. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  24248. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  24249. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  24250. var tempVector = BABYLON.Tmp.Vector3[0];
  24251. var finalMatrix = BABYLON.Tmp.Matrix[0];
  24252. var tempMatrix = BABYLON.Tmp.Matrix[1];
  24253. var matWeightIdx = 0;
  24254. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  24255. finalMatrix.reset();
  24256. var inf;
  24257. var weight;
  24258. for (inf = 0; inf < 4; inf++) {
  24259. weight = matricesWeightsData[matWeightIdx + inf];
  24260. if (weight <= 0)
  24261. break;
  24262. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  24263. finalMatrix.addToSelf(tempMatrix);
  24264. }
  24265. if (needExtras) {
  24266. for (inf = 0; inf < 4; inf++) {
  24267. weight = matricesWeightsExtraData[matWeightIdx + inf];
  24268. if (weight <= 0)
  24269. break;
  24270. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  24271. finalMatrix.addToSelf(tempMatrix);
  24272. }
  24273. }
  24274. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  24275. tempVector.toArray(data, index);
  24276. }
  24277. }
  24278. }
  24279. return data;
  24280. };
  24281. Mesh.prototype._createGlobalSubMesh = function (force) {
  24282. var totalVertices = this.getTotalVertices();
  24283. if (!totalVertices || !this.getIndices()) {
  24284. return null;
  24285. }
  24286. // Check if we need to recreate the submeshes
  24287. if (this.subMeshes && this.subMeshes.length > 0) {
  24288. var ib = this.getIndices();
  24289. if (!ib) {
  24290. return null;
  24291. }
  24292. var totalIndices = ib.length;
  24293. var needToRecreate = false;
  24294. if (force) {
  24295. needToRecreate = true;
  24296. }
  24297. else {
  24298. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  24299. var submesh = _a[_i];
  24300. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  24301. needToRecreate = true;
  24302. break;
  24303. }
  24304. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  24305. needToRecreate = true;
  24306. break;
  24307. }
  24308. }
  24309. }
  24310. if (!needToRecreate) {
  24311. return this.subMeshes[0];
  24312. }
  24313. }
  24314. this.releaseSubMeshes();
  24315. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  24316. };
  24317. Mesh.prototype.subdivide = function (count) {
  24318. if (count < 1) {
  24319. return;
  24320. }
  24321. var totalIndices = this.getTotalIndices();
  24322. var subdivisionSize = (totalIndices / count) | 0;
  24323. var offset = 0;
  24324. // Ensure that subdivisionSize is a multiple of 3
  24325. while (subdivisionSize % 3 !== 0) {
  24326. subdivisionSize++;
  24327. }
  24328. this.releaseSubMeshes();
  24329. for (var index = 0; index < count; index++) {
  24330. if (offset >= totalIndices) {
  24331. break;
  24332. }
  24333. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  24334. offset += subdivisionSize;
  24335. }
  24336. this.synchronizeInstances();
  24337. };
  24338. /**
  24339. * Sets the vertex data of the mesh geometry for the requested `kind`.
  24340. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  24341. * The `data` are either a numeric array either a Float32Array.
  24342. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  24343. * 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).
  24344. * Note that a new underlying VertexBuffer object is created each call.
  24345. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  24346. *
  24347. * Possible `kind` values :
  24348. * - BABYLON.VertexBuffer.PositionKind
  24349. * - BABYLON.VertexBuffer.UVKind
  24350. * - BABYLON.VertexBuffer.UV2Kind
  24351. * - BABYLON.VertexBuffer.UV3Kind
  24352. * - BABYLON.VertexBuffer.UV4Kind
  24353. * - BABYLON.VertexBuffer.UV5Kind
  24354. * - BABYLON.VertexBuffer.UV6Kind
  24355. * - BABYLON.VertexBuffer.ColorKind
  24356. * - BABYLON.VertexBuffer.MatricesIndicesKind
  24357. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  24358. * - BABYLON.VertexBuffer.MatricesWeightsKind
  24359. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  24360. *
  24361. * Returns the Mesh.
  24362. */
  24363. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  24364. if (updatable === void 0) { updatable = false; }
  24365. if (!this._geometry) {
  24366. var vertexData = new BABYLON.VertexData();
  24367. vertexData.set(data, kind);
  24368. var scene = this.getScene();
  24369. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  24370. }
  24371. else {
  24372. this._geometry.setVerticesData(kind, data, updatable, stride);
  24373. }
  24374. return this;
  24375. };
  24376. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  24377. if (updatable === void 0) { updatable = true; }
  24378. var vb = this.getVertexBuffer(kind);
  24379. if (!vb || vb.isUpdatable() === updatable) {
  24380. return;
  24381. }
  24382. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  24383. };
  24384. /**
  24385. * Sets the mesh VertexBuffer.
  24386. * Returns the Mesh.
  24387. */
  24388. Mesh.prototype.setVerticesBuffer = function (buffer) {
  24389. if (!this._geometry) {
  24390. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  24391. }
  24392. this._geometry.setVerticesBuffer(buffer);
  24393. return this;
  24394. };
  24395. /**
  24396. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  24397. * If the mesh has no geometry, it is simply returned as it is.
  24398. * The `data` are either a numeric array either a Float32Array.
  24399. * No new underlying VertexBuffer object is created.
  24400. * 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.
  24401. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  24402. *
  24403. * Possible `kind` values :
  24404. * - BABYLON.VertexBuffer.PositionKind
  24405. * - BABYLON.VertexBuffer.UVKind
  24406. * - BABYLON.VertexBuffer.UV2Kind
  24407. * - BABYLON.VertexBuffer.UV3Kind
  24408. * - BABYLON.VertexBuffer.UV4Kind
  24409. * - BABYLON.VertexBuffer.UV5Kind
  24410. * - BABYLON.VertexBuffer.UV6Kind
  24411. * - BABYLON.VertexBuffer.ColorKind
  24412. * - BABYLON.VertexBuffer.MatricesIndicesKind
  24413. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  24414. * - BABYLON.VertexBuffer.MatricesWeightsKind
  24415. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  24416. *
  24417. * Returns the Mesh.
  24418. */
  24419. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  24420. if (!this._geometry) {
  24421. return this;
  24422. }
  24423. if (!makeItUnique) {
  24424. this._geometry.updateVerticesData(kind, data, updateExtends);
  24425. }
  24426. else {
  24427. this.makeGeometryUnique();
  24428. this.updateVerticesData(kind, data, updateExtends, false);
  24429. }
  24430. return this;
  24431. };
  24432. /**
  24433. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  24434. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  24435. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  24436. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  24437. * Returns the Mesh.
  24438. */
  24439. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  24440. if (computeNormals === void 0) { computeNormals = true; }
  24441. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24442. if (!positions) {
  24443. return this;
  24444. }
  24445. positionFunction(positions);
  24446. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  24447. if (computeNormals) {
  24448. var indices = this.getIndices();
  24449. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24450. if (!normals) {
  24451. return this;
  24452. }
  24453. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  24454. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  24455. }
  24456. return this;
  24457. };
  24458. /**
  24459. * Creates a un-shared specific occurence of the geometry for the mesh.
  24460. * Returns the Mesh.
  24461. */
  24462. Mesh.prototype.makeGeometryUnique = function () {
  24463. if (!this._geometry) {
  24464. return this;
  24465. }
  24466. var oldGeometry = this._geometry;
  24467. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  24468. oldGeometry.releaseForMesh(this, true);
  24469. geometry.applyToMesh(this);
  24470. return this;
  24471. };
  24472. /**
  24473. * Sets the mesh indices.
  24474. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  24475. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  24476. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  24477. * This method creates a new index buffer each call.
  24478. * Returns the Mesh.
  24479. */
  24480. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  24481. if (totalVertices === void 0) { totalVertices = null; }
  24482. if (updatable === void 0) { updatable = false; }
  24483. if (!this._geometry) {
  24484. var vertexData = new BABYLON.VertexData();
  24485. vertexData.indices = indices;
  24486. var scene = this.getScene();
  24487. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  24488. }
  24489. else {
  24490. this._geometry.setIndices(indices, totalVertices, updatable);
  24491. }
  24492. return this;
  24493. };
  24494. /**
  24495. * Update the current index buffer
  24496. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  24497. * Returns the Mesh.
  24498. */
  24499. Mesh.prototype.updateIndices = function (indices, offset) {
  24500. if (!this._geometry) {
  24501. return this;
  24502. }
  24503. this._geometry.updateIndices(indices, offset);
  24504. return this;
  24505. };
  24506. /**
  24507. * Invert the geometry to move from a right handed system to a left handed one.
  24508. * Returns the Mesh.
  24509. */
  24510. Mesh.prototype.toLeftHanded = function () {
  24511. if (!this._geometry) {
  24512. return this;
  24513. }
  24514. this._geometry.toLeftHanded();
  24515. return this;
  24516. };
  24517. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  24518. if (!this._geometry) {
  24519. return this;
  24520. }
  24521. var engine = this.getScene().getEngine();
  24522. // Wireframe
  24523. var indexToBind;
  24524. if (this._unIndexed) {
  24525. indexToBind = null;
  24526. }
  24527. else {
  24528. switch (fillMode) {
  24529. case BABYLON.Material.PointFillMode:
  24530. indexToBind = null;
  24531. break;
  24532. case BABYLON.Material.WireFrameFillMode:
  24533. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  24534. break;
  24535. default:
  24536. case BABYLON.Material.TriangleFillMode:
  24537. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  24538. break;
  24539. }
  24540. }
  24541. // VBOs
  24542. this._geometry._bind(effect, indexToBind);
  24543. return this;
  24544. };
  24545. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  24546. if (alternate === void 0) { alternate = false; }
  24547. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  24548. return this;
  24549. }
  24550. this.onBeforeDrawObservable.notifyObservers(this);
  24551. var scene = this.getScene();
  24552. var engine = scene.getEngine();
  24553. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  24554. // or triangles as points
  24555. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  24556. }
  24557. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  24558. // Triangles as wireframe
  24559. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  24560. }
  24561. else {
  24562. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  24563. }
  24564. if (scene._isAlternateRenderingEnabled && !alternate) {
  24565. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  24566. if (!effect || !scene.activeCamera) {
  24567. return this;
  24568. }
  24569. scene._switchToAlternateCameraConfiguration(true);
  24570. this._effectiveMaterial.bindView(effect);
  24571. this._effectiveMaterial.bindViewProjection(effect);
  24572. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  24573. this._draw(subMesh, fillMode, instancesCount, true);
  24574. engine.setViewport(scene.activeCamera.viewport);
  24575. scene._switchToAlternateCameraConfiguration(false);
  24576. this._effectiveMaterial.bindView(effect);
  24577. this._effectiveMaterial.bindViewProjection(effect);
  24578. }
  24579. return this;
  24580. };
  24581. /**
  24582. * Registers for this mesh a javascript function called just before the rendering process.
  24583. * This function is passed the current mesh.
  24584. * Return the Mesh.
  24585. */
  24586. Mesh.prototype.registerBeforeRender = function (func) {
  24587. this.onBeforeRenderObservable.add(func);
  24588. return this;
  24589. };
  24590. /**
  24591. * Disposes a previously registered javascript function called before the rendering.
  24592. * This function is passed the current mesh.
  24593. * Returns the Mesh.
  24594. */
  24595. Mesh.prototype.unregisterBeforeRender = function (func) {
  24596. this.onBeforeRenderObservable.removeCallback(func);
  24597. return this;
  24598. };
  24599. /**
  24600. * Registers for this mesh a javascript function called just after the rendering is complete.
  24601. * This function is passed the current mesh.
  24602. * Returns the Mesh.
  24603. */
  24604. Mesh.prototype.registerAfterRender = function (func) {
  24605. this.onAfterRenderObservable.add(func);
  24606. return this;
  24607. };
  24608. /**
  24609. * Disposes a previously registered javascript function called after the rendering.
  24610. * This function is passed the current mesh.
  24611. * Return the Mesh.
  24612. */
  24613. Mesh.prototype.unregisterAfterRender = function (func) {
  24614. this.onAfterRenderObservable.removeCallback(func);
  24615. return this;
  24616. };
  24617. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  24618. var scene = this.getScene();
  24619. this._batchCache.mustReturn = false;
  24620. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  24621. this._batchCache.visibleInstances[subMeshId] = null;
  24622. if (this._visibleInstances) {
  24623. var currentRenderId = scene.getRenderId();
  24624. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  24625. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  24626. var selfRenderId = this._renderId;
  24627. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  24628. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  24629. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  24630. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  24631. }
  24632. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  24633. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  24634. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  24635. this._batchCache.mustReturn = true;
  24636. return this._batchCache;
  24637. }
  24638. if (currentRenderId !== selfRenderId) {
  24639. this._batchCache.renderSelf[subMeshId] = false;
  24640. }
  24641. }
  24642. this._renderIdForInstances[subMeshId] = currentRenderId;
  24643. }
  24644. return this._batchCache;
  24645. };
  24646. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  24647. var visibleInstances = batch.visibleInstances[subMesh._id];
  24648. if (!visibleInstances) {
  24649. return this;
  24650. }
  24651. var matricesCount = visibleInstances.length + 1;
  24652. var bufferSize = matricesCount * 16 * 4;
  24653. var currentInstancesBufferSize = this._instancesBufferSize;
  24654. var instancesBuffer = this._instancesBuffer;
  24655. while (this._instancesBufferSize < bufferSize) {
  24656. this._instancesBufferSize *= 2;
  24657. }
  24658. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  24659. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  24660. }
  24661. var offset = 0;
  24662. var instancesCount = 0;
  24663. var world = this.getWorldMatrix();
  24664. if (batch.renderSelf[subMesh._id]) {
  24665. world.copyToArray(this._instancesData, offset);
  24666. offset += 16;
  24667. instancesCount++;
  24668. }
  24669. if (visibleInstances) {
  24670. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  24671. var instance = visibleInstances[instanceIndex];
  24672. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  24673. offset += 16;
  24674. instancesCount++;
  24675. }
  24676. }
  24677. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  24678. if (instancesBuffer) {
  24679. instancesBuffer.dispose();
  24680. }
  24681. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  24682. this._instancesBuffer = instancesBuffer;
  24683. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  24684. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  24685. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  24686. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  24687. }
  24688. else {
  24689. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  24690. }
  24691. this._bind(subMesh, effect, fillMode);
  24692. this._draw(subMesh, fillMode, instancesCount);
  24693. engine.unbindInstanceAttributes();
  24694. return this;
  24695. };
  24696. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  24697. var scene = this.getScene();
  24698. var engine = scene.getEngine();
  24699. if (hardwareInstancedRendering) {
  24700. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  24701. }
  24702. else {
  24703. if (batch.renderSelf[subMesh._id]) {
  24704. // Draw
  24705. if (onBeforeDraw) {
  24706. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  24707. }
  24708. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  24709. }
  24710. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  24711. if (visibleInstancesForSubMesh) {
  24712. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  24713. var instance = visibleInstancesForSubMesh[instanceIndex];
  24714. // World
  24715. var world = instance.getWorldMatrix();
  24716. if (onBeforeDraw) {
  24717. onBeforeDraw(true, world, effectiveMaterial);
  24718. }
  24719. // Draw
  24720. this._draw(subMesh, fillMode);
  24721. }
  24722. }
  24723. }
  24724. return this;
  24725. };
  24726. /**
  24727. * Triggers the draw call for the mesh.
  24728. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  24729. * Returns the Mesh.
  24730. */
  24731. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  24732. this.checkOcclusionQuery();
  24733. if (this._isOccluded) {
  24734. return this;
  24735. }
  24736. var scene = this.getScene();
  24737. // Managing instances
  24738. var batch = this._getInstancesRenderList(subMesh._id);
  24739. if (batch.mustReturn) {
  24740. return this;
  24741. }
  24742. // Checking geometry state
  24743. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  24744. return this;
  24745. }
  24746. this.onBeforeRenderObservable.notifyObservers(this);
  24747. var engine = scene.getEngine();
  24748. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  24749. // Material
  24750. var material = subMesh.getMaterial();
  24751. if (!material) {
  24752. return this;
  24753. }
  24754. this._effectiveMaterial = material;
  24755. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  24756. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  24757. return this;
  24758. }
  24759. }
  24760. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  24761. return this;
  24762. }
  24763. // Alpha mode
  24764. if (enableAlphaMode) {
  24765. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  24766. }
  24767. // Outline - step 1
  24768. var savedDepthWrite = engine.getDepthWrite();
  24769. if (this.renderOutline) {
  24770. engine.setDepthWrite(false);
  24771. scene.getOutlineRenderer().render(subMesh, batch);
  24772. engine.setDepthWrite(savedDepthWrite);
  24773. }
  24774. var effect;
  24775. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  24776. effect = subMesh.effect;
  24777. }
  24778. else {
  24779. effect = this._effectiveMaterial.getEffect();
  24780. }
  24781. if (!effect) {
  24782. return this;
  24783. }
  24784. var sideOrientation = this.overrideMaterialSideOrientation;
  24785. if (sideOrientation == null) {
  24786. sideOrientation = this._effectiveMaterial.sideOrientation;
  24787. if (this._getWorldMatrixDeterminant() < 0) {
  24788. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  24789. }
  24790. }
  24791. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  24792. if (this._effectiveMaterial.forceDepthWrite) {
  24793. engine.setDepthWrite(true);
  24794. }
  24795. // Bind
  24796. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  24797. if (!hardwareInstancedRendering) {
  24798. this._bind(subMesh, effect, fillMode);
  24799. }
  24800. var world = this.getWorldMatrix();
  24801. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  24802. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  24803. }
  24804. else {
  24805. this._effectiveMaterial.bind(world, this);
  24806. }
  24807. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  24808. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  24809. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  24810. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  24811. }
  24812. // Draw
  24813. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  24814. // Unbind
  24815. this._effectiveMaterial.unbind();
  24816. // Outline - step 2
  24817. if (this.renderOutline && savedDepthWrite) {
  24818. engine.setDepthWrite(true);
  24819. engine.setColorWrite(false);
  24820. scene.getOutlineRenderer().render(subMesh, batch);
  24821. engine.setColorWrite(true);
  24822. }
  24823. // Overlay
  24824. if (this.renderOverlay) {
  24825. var currentMode = engine.getAlphaMode();
  24826. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  24827. scene.getOutlineRenderer().render(subMesh, batch, true);
  24828. engine.setAlphaMode(currentMode);
  24829. }
  24830. this.onAfterRenderObservable.notifyObservers(this);
  24831. return this;
  24832. };
  24833. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  24834. if (isInstance && effectiveMaterial) {
  24835. effectiveMaterial.bindOnlyWorldMatrix(world);
  24836. }
  24837. };
  24838. /**
  24839. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  24840. */
  24841. Mesh.prototype.getEmittedParticleSystems = function () {
  24842. var results = new Array();
  24843. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  24844. var particleSystem = this.getScene().particleSystems[index];
  24845. if (particleSystem.emitter === this) {
  24846. results.push(particleSystem);
  24847. }
  24848. }
  24849. return results;
  24850. };
  24851. /**
  24852. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  24853. */
  24854. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  24855. var results = new Array();
  24856. var descendants = this.getDescendants();
  24857. descendants.push(this);
  24858. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  24859. var particleSystem = this.getScene().particleSystems[index];
  24860. var emitter = particleSystem.emitter;
  24861. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  24862. results.push(particleSystem);
  24863. }
  24864. }
  24865. return results;
  24866. };
  24867. Mesh.prototype._checkDelayState = function () {
  24868. var scene = this.getScene();
  24869. if (this._geometry) {
  24870. this._geometry.load(scene);
  24871. }
  24872. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24873. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  24874. this._queueLoad(scene);
  24875. }
  24876. return this;
  24877. };
  24878. Mesh.prototype._queueLoad = function (scene) {
  24879. var _this = this;
  24880. scene._addPendingData(this);
  24881. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  24882. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  24883. if (data instanceof ArrayBuffer) {
  24884. _this._delayLoadingFunction(data, _this);
  24885. }
  24886. else {
  24887. _this._delayLoadingFunction(JSON.parse(data), _this);
  24888. }
  24889. _this.instances.forEach(function (instance) {
  24890. instance._syncSubMeshes();
  24891. });
  24892. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24893. scene._removePendingData(_this);
  24894. }, function () { }, scene.database, getBinaryData);
  24895. return this;
  24896. };
  24897. /**
  24898. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  24899. */
  24900. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  24901. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  24902. return false;
  24903. }
  24904. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  24905. return false;
  24906. }
  24907. this._checkDelayState();
  24908. return true;
  24909. };
  24910. /**
  24911. * Sets the mesh material by the material or multiMaterial `id` property.
  24912. * The material `id` is a string identifying the material or the multiMaterial.
  24913. * This method returns the Mesh.
  24914. */
  24915. Mesh.prototype.setMaterialByID = function (id) {
  24916. var materials = this.getScene().materials;
  24917. var index;
  24918. for (index = materials.length - 1; index > -1; index--) {
  24919. if (materials[index].id === id) {
  24920. this.material = materials[index];
  24921. return this;
  24922. }
  24923. }
  24924. // Multi
  24925. var multiMaterials = this.getScene().multiMaterials;
  24926. for (index = multiMaterials.length - 1; index > -1; index--) {
  24927. if (multiMaterials[index].id === id) {
  24928. this.material = multiMaterials[index];
  24929. return this;
  24930. }
  24931. }
  24932. return this;
  24933. };
  24934. /**
  24935. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  24936. */
  24937. Mesh.prototype.getAnimatables = function () {
  24938. var results = new Array();
  24939. if (this.material) {
  24940. results.push(this.material);
  24941. }
  24942. if (this.skeleton) {
  24943. results.push(this.skeleton);
  24944. }
  24945. return results;
  24946. };
  24947. /**
  24948. * Modifies the mesh geometry according to the passed transformation matrix.
  24949. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  24950. * The mesh normals are modified accordingly the same transformation.
  24951. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  24952. * Note that, under the hood, this method sets a new VertexBuffer each call.
  24953. * Returns the Mesh.
  24954. */
  24955. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  24956. // Position
  24957. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24958. return this;
  24959. }
  24960. var submeshes = this.subMeshes.splice(0);
  24961. this._resetPointsArrayCache();
  24962. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24963. var temp = new Array();
  24964. var index;
  24965. for (index = 0; index < data.length; index += 3) {
  24966. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  24967. }
  24968. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  24969. // Normals
  24970. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24971. return this;
  24972. }
  24973. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24974. temp = [];
  24975. for (index = 0; index < data.length; index += 3) {
  24976. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  24977. }
  24978. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  24979. // flip faces?
  24980. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  24981. this.flipFaces();
  24982. }
  24983. // Restore submeshes
  24984. this.releaseSubMeshes();
  24985. this.subMeshes = submeshes;
  24986. return this;
  24987. };
  24988. /**
  24989. * Modifies the mesh geometry according to its own current World Matrix.
  24990. * The mesh World Matrix is then reset.
  24991. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  24992. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  24993. * Note that, under the hood, this method sets a new VertexBuffer each call.
  24994. * Returns the Mesh.
  24995. */
  24996. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  24997. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  24998. this.scaling.copyFromFloats(1, 1, 1);
  24999. this.position.copyFromFloats(0, 0, 0);
  25000. this.rotation.copyFromFloats(0, 0, 0);
  25001. //only if quaternion is already set
  25002. if (this.rotationQuaternion) {
  25003. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  25004. }
  25005. this._worldMatrix = BABYLON.Matrix.Identity();
  25006. return this;
  25007. };
  25008. Object.defineProperty(Mesh.prototype, "_positions", {
  25009. // Cache
  25010. get: function () {
  25011. if (this._geometry) {
  25012. return this._geometry._positions;
  25013. }
  25014. return null;
  25015. },
  25016. enumerable: true,
  25017. configurable: true
  25018. });
  25019. Mesh.prototype._resetPointsArrayCache = function () {
  25020. if (this._geometry) {
  25021. this._geometry._resetPointsArrayCache();
  25022. }
  25023. return this;
  25024. };
  25025. Mesh.prototype._generatePointsArray = function () {
  25026. if (this._geometry) {
  25027. return this._geometry._generatePointsArray();
  25028. }
  25029. return false;
  25030. };
  25031. /**
  25032. * Returns a new Mesh object generated from the current mesh properties.
  25033. * This method must not get confused with createInstance().
  25034. * The parameter `name` is a string, the name given to the new mesh.
  25035. * The optional parameter `newParent` can be any Node object (default `null`).
  25036. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  25037. * 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.
  25038. */
  25039. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  25040. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  25041. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  25042. };
  25043. /**
  25044. * Disposes the Mesh.
  25045. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  25046. * Returns nothing.
  25047. */
  25048. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  25049. var _this = this;
  25050. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  25051. this.morphTargetManager = null;
  25052. if (this._geometry) {
  25053. this._geometry.releaseForMesh(this, true);
  25054. }
  25055. // Sources
  25056. var meshes = this.getScene().meshes;
  25057. meshes.forEach(function (abstractMesh) {
  25058. var mesh = abstractMesh;
  25059. if (mesh._source && mesh._source === _this) {
  25060. mesh._source = null;
  25061. }
  25062. });
  25063. this._source = null;
  25064. // Instances
  25065. if (this._instancesBuffer) {
  25066. this._instancesBuffer.dispose();
  25067. this._instancesBuffer = null;
  25068. }
  25069. while (this.instances.length) {
  25070. this.instances[0].dispose();
  25071. }
  25072. // Highlight layers.
  25073. var highlightLayers = this.getScene().highlightLayers;
  25074. for (var i = 0; i < highlightLayers.length; i++) {
  25075. var highlightLayer = highlightLayers[i];
  25076. if (highlightLayer) {
  25077. highlightLayer.removeMesh(this);
  25078. highlightLayer.removeExcludedMesh(this);
  25079. }
  25080. }
  25081. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  25082. };
  25083. /**
  25084. * Modifies the mesh geometry according to a displacement map.
  25085. * 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.
  25086. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  25087. * This method returns nothing.
  25088. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  25089. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  25090. * 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.
  25091. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  25092. * The parameter `uvScale` is an optional vector2 used to scale UV.
  25093. *
  25094. * Returns the Mesh.
  25095. */
  25096. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  25097. var _this = this;
  25098. var scene = this.getScene();
  25099. var onload = function (img) {
  25100. // Getting height map data
  25101. var canvas = document.createElement("canvas");
  25102. var context = canvas.getContext("2d");
  25103. var heightMapWidth = img.width;
  25104. var heightMapHeight = img.height;
  25105. canvas.width = heightMapWidth;
  25106. canvas.height = heightMapHeight;
  25107. context.drawImage(img, 0, 0);
  25108. // Create VertexData from map data
  25109. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  25110. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  25111. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  25112. //execute success callback, if set
  25113. if (onSuccess) {
  25114. onSuccess(_this);
  25115. }
  25116. };
  25117. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  25118. return this;
  25119. };
  25120. /**
  25121. * Modifies the mesh geometry according to a displacementMap buffer.
  25122. * 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.
  25123. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  25124. * This method returns nothing.
  25125. * 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.
  25126. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  25127. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  25128. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  25129. * The parameter `uvScale` is an optional vector2 used to scale UV.
  25130. *
  25131. * Returns the Mesh.
  25132. */
  25133. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  25134. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  25135. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  25136. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25137. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  25138. return this;
  25139. }
  25140. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25141. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25142. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  25143. var position = BABYLON.Vector3.Zero();
  25144. var normal = BABYLON.Vector3.Zero();
  25145. var uv = BABYLON.Vector2.Zero();
  25146. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  25147. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  25148. for (var index = 0; index < positions.length; index += 3) {
  25149. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  25150. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  25151. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  25152. // Compute height
  25153. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  25154. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  25155. var pos = (u + v * heightMapWidth) * 4;
  25156. var r = buffer[pos] / 255.0;
  25157. var g = buffer[pos + 1] / 255.0;
  25158. var b = buffer[pos + 2] / 255.0;
  25159. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  25160. normal.normalize();
  25161. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  25162. position = position.add(normal);
  25163. position.toArray(positions, index);
  25164. }
  25165. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  25166. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  25167. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  25168. return this;
  25169. };
  25170. /**
  25171. * Modify the mesh to get a flat shading rendering.
  25172. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  25173. * This method returns the Mesh.
  25174. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  25175. */
  25176. Mesh.prototype.convertToFlatShadedMesh = function () {
  25177. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  25178. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  25179. var kinds = this.getVerticesDataKinds();
  25180. var vbs = {};
  25181. var data = {};
  25182. var newdata = {};
  25183. var updatableNormals = false;
  25184. var kindIndex;
  25185. var kind;
  25186. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  25187. kind = kinds[kindIndex];
  25188. var vertexBuffer = this.getVertexBuffer(kind);
  25189. if (kind === BABYLON.VertexBuffer.NormalKind) {
  25190. updatableNormals = vertexBuffer.isUpdatable();
  25191. kinds.splice(kindIndex, 1);
  25192. kindIndex--;
  25193. continue;
  25194. }
  25195. vbs[kind] = vertexBuffer;
  25196. data[kind] = vbs[kind].getData();
  25197. newdata[kind] = [];
  25198. }
  25199. // Save previous submeshes
  25200. var previousSubmeshes = this.subMeshes.slice(0);
  25201. var indices = this.getIndices();
  25202. var totalIndices = this.getTotalIndices();
  25203. // Generating unique vertices per face
  25204. var index;
  25205. for (index = 0; index < totalIndices; index++) {
  25206. var vertexIndex = indices[index];
  25207. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  25208. kind = kinds[kindIndex];
  25209. var stride = vbs[kind].getStrideSize();
  25210. for (var offset = 0; offset < stride; offset++) {
  25211. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  25212. }
  25213. }
  25214. }
  25215. // Updating faces & normal
  25216. var normals = [];
  25217. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  25218. for (index = 0; index < totalIndices; index += 3) {
  25219. indices[index] = index;
  25220. indices[index + 1] = index + 1;
  25221. indices[index + 2] = index + 2;
  25222. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  25223. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  25224. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  25225. var p1p2 = p1.subtract(p2);
  25226. var p3p2 = p3.subtract(p2);
  25227. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  25228. // Store same normals for every vertex
  25229. for (var localIndex = 0; localIndex < 3; localIndex++) {
  25230. normals.push(normal.x);
  25231. normals.push(normal.y);
  25232. normals.push(normal.z);
  25233. }
  25234. }
  25235. this.setIndices(indices);
  25236. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  25237. // Updating vertex buffers
  25238. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  25239. kind = kinds[kindIndex];
  25240. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  25241. }
  25242. // Updating submeshes
  25243. this.releaseSubMeshes();
  25244. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  25245. var previousOne = previousSubmeshes[submeshIndex];
  25246. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  25247. }
  25248. this.synchronizeInstances();
  25249. return this;
  25250. };
  25251. /**
  25252. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  25253. * In other words, more vertices, no more indices and a single bigger VBO.
  25254. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  25255. * Returns the Mesh.
  25256. */
  25257. Mesh.prototype.convertToUnIndexedMesh = function () {
  25258. /// <summary>Remove indices by unfolding faces into buffers</summary>
  25259. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  25260. var kinds = this.getVerticesDataKinds();
  25261. var vbs = {};
  25262. var data = {};
  25263. var newdata = {};
  25264. var kindIndex;
  25265. var kind;
  25266. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  25267. kind = kinds[kindIndex];
  25268. var vertexBuffer = this.getVertexBuffer(kind);
  25269. vbs[kind] = vertexBuffer;
  25270. data[kind] = vbs[kind].getData();
  25271. newdata[kind] = [];
  25272. }
  25273. // Save previous submeshes
  25274. var previousSubmeshes = this.subMeshes.slice(0);
  25275. var indices = this.getIndices();
  25276. var totalIndices = this.getTotalIndices();
  25277. // Generating unique vertices per face
  25278. var index;
  25279. for (index = 0; index < totalIndices; index++) {
  25280. var vertexIndex = indices[index];
  25281. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  25282. kind = kinds[kindIndex];
  25283. var stride = vbs[kind].getStrideSize();
  25284. for (var offset = 0; offset < stride; offset++) {
  25285. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  25286. }
  25287. }
  25288. }
  25289. // Updating indices
  25290. for (index = 0; index < totalIndices; index += 3) {
  25291. indices[index] = index;
  25292. indices[index + 1] = index + 1;
  25293. indices[index + 2] = index + 2;
  25294. }
  25295. this.setIndices(indices);
  25296. // Updating vertex buffers
  25297. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  25298. kind = kinds[kindIndex];
  25299. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  25300. }
  25301. // Updating submeshes
  25302. this.releaseSubMeshes();
  25303. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  25304. var previousOne = previousSubmeshes[submeshIndex];
  25305. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  25306. }
  25307. this._unIndexed = true;
  25308. this.synchronizeInstances();
  25309. return this;
  25310. };
  25311. /**
  25312. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  25313. * This method returns the Mesh.
  25314. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  25315. */
  25316. Mesh.prototype.flipFaces = function (flipNormals) {
  25317. if (flipNormals === void 0) { flipNormals = false; }
  25318. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  25319. var i;
  25320. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  25321. for (i = 0; i < vertex_data.normals.length; i++) {
  25322. vertex_data.normals[i] *= -1;
  25323. }
  25324. }
  25325. if (vertex_data.indices) {
  25326. var temp;
  25327. for (i = 0; i < vertex_data.indices.length; i += 3) {
  25328. // reassign indices
  25329. temp = vertex_data.indices[i + 1];
  25330. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  25331. vertex_data.indices[i + 2] = temp;
  25332. }
  25333. }
  25334. vertex_data.applyToMesh(this);
  25335. return this;
  25336. };
  25337. // Instances
  25338. /**
  25339. * Creates a new InstancedMesh object from the mesh model.
  25340. * An instance shares the same properties and the same material than its model.
  25341. * Only these properties of each instance can then be set individually :
  25342. * - position
  25343. * - rotation
  25344. * - rotationQuaternion
  25345. * - setPivotMatrix
  25346. * - scaling
  25347. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  25348. * Warning : this method is not supported for Line mesh and LineSystem
  25349. */
  25350. Mesh.prototype.createInstance = function (name) {
  25351. return new BABYLON.InstancedMesh(name, this);
  25352. };
  25353. /**
  25354. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  25355. * After this call, all the mesh instances have the same submeshes than the current mesh.
  25356. * This method returns the Mesh.
  25357. */
  25358. Mesh.prototype.synchronizeInstances = function () {
  25359. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  25360. var instance = this.instances[instanceIndex];
  25361. instance._syncSubMeshes();
  25362. }
  25363. return this;
  25364. };
  25365. /**
  25366. * Simplify the mesh according to the given array of settings.
  25367. * Function will return immediately and will simplify async. It returns the Mesh.
  25368. * @param settings a collection of simplification settings.
  25369. * @param parallelProcessing should all levels calculate parallel or one after the other.
  25370. * @param type the type of simplification to run.
  25371. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  25372. */
  25373. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  25374. if (parallelProcessing === void 0) { parallelProcessing = true; }
  25375. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  25376. this.getScene().simplificationQueue.addTask({
  25377. settings: settings,
  25378. parallelProcessing: parallelProcessing,
  25379. mesh: this,
  25380. simplificationType: simplificationType,
  25381. successCallback: successCallback
  25382. });
  25383. return this;
  25384. };
  25385. /**
  25386. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  25387. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  25388. * This should be used together with the simplification to avoid disappearing triangles.
  25389. * Returns the Mesh.
  25390. * @param successCallback an optional success callback to be called after the optimization finished.
  25391. */
  25392. Mesh.prototype.optimizeIndices = function (successCallback) {
  25393. var _this = this;
  25394. var indices = this.getIndices();
  25395. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25396. if (!positions || !indices) {
  25397. return this;
  25398. }
  25399. var vectorPositions = new Array();
  25400. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  25401. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  25402. }
  25403. var dupes = new Array();
  25404. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  25405. var realPos = vectorPositions.length - 1 - iteration;
  25406. var testedPosition = vectorPositions[realPos];
  25407. for (var j = 0; j < realPos; ++j) {
  25408. var againstPosition = vectorPositions[j];
  25409. if (testedPosition.equals(againstPosition)) {
  25410. dupes[realPos] = j;
  25411. break;
  25412. }
  25413. }
  25414. }, function () {
  25415. for (var i = 0; i < indices.length; ++i) {
  25416. indices[i] = dupes[indices[i]] || indices[i];
  25417. }
  25418. //indices are now reordered
  25419. var originalSubMeshes = _this.subMeshes.slice(0);
  25420. _this.setIndices(indices);
  25421. _this.subMeshes = originalSubMeshes;
  25422. if (successCallback) {
  25423. successCallback(_this);
  25424. }
  25425. });
  25426. return this;
  25427. };
  25428. Mesh.prototype.serialize = function (serializationObject) {
  25429. serializationObject.name = this.name;
  25430. serializationObject.id = this.id;
  25431. serializationObject.type = this.getClassName();
  25432. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  25433. serializationObject.tags = BABYLON.Tags.GetTags(this);
  25434. }
  25435. serializationObject.position = this.position.asArray();
  25436. if (this.rotationQuaternion) {
  25437. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  25438. }
  25439. else if (this.rotation) {
  25440. serializationObject.rotation = this.rotation.asArray();
  25441. }
  25442. serializationObject.scaling = this.scaling.asArray();
  25443. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  25444. serializationObject.isEnabled = this.isEnabled(false);
  25445. serializationObject.isVisible = this.isVisible;
  25446. serializationObject.infiniteDistance = this.infiniteDistance;
  25447. serializationObject.pickable = this.isPickable;
  25448. serializationObject.receiveShadows = this.receiveShadows;
  25449. serializationObject.billboardMode = this.billboardMode;
  25450. serializationObject.visibility = this.visibility;
  25451. serializationObject.checkCollisions = this.checkCollisions;
  25452. serializationObject.isBlocker = this.isBlocker;
  25453. // Parent
  25454. if (this.parent) {
  25455. serializationObject.parentId = this.parent.id;
  25456. }
  25457. // Geometry
  25458. serializationObject.isUnIndexed = this.isUnIndexed;
  25459. var geometry = this._geometry;
  25460. if (geometry) {
  25461. var geometryId = geometry.id;
  25462. serializationObject.geometryId = geometryId;
  25463. // SubMeshes
  25464. serializationObject.subMeshes = [];
  25465. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  25466. var subMesh = this.subMeshes[subIndex];
  25467. serializationObject.subMeshes.push({
  25468. materialIndex: subMesh.materialIndex,
  25469. verticesStart: subMesh.verticesStart,
  25470. verticesCount: subMesh.verticesCount,
  25471. indexStart: subMesh.indexStart,
  25472. indexCount: subMesh.indexCount
  25473. });
  25474. }
  25475. }
  25476. // Material
  25477. if (this.material) {
  25478. serializationObject.materialId = this.material.id;
  25479. }
  25480. else {
  25481. this.material = null;
  25482. }
  25483. // Morph targets
  25484. if (this.morphTargetManager) {
  25485. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  25486. }
  25487. // Skeleton
  25488. if (this.skeleton) {
  25489. serializationObject.skeletonId = this.skeleton.id;
  25490. }
  25491. // Physics
  25492. //TODO implement correct serialization for physics impostors.
  25493. var impostor = this.getPhysicsImpostor();
  25494. if (impostor) {
  25495. serializationObject.physicsMass = impostor.getParam("mass");
  25496. serializationObject.physicsFriction = impostor.getParam("friction");
  25497. serializationObject.physicsRestitution = impostor.getParam("mass");
  25498. serializationObject.physicsImpostor = impostor.type;
  25499. }
  25500. // Metadata
  25501. if (this.metadata) {
  25502. serializationObject.metadata = this.metadata;
  25503. }
  25504. // Instances
  25505. serializationObject.instances = [];
  25506. for (var index = 0; index < this.instances.length; index++) {
  25507. var instance = this.instances[index];
  25508. var serializationInstance = {
  25509. name: instance.name,
  25510. id: instance.id,
  25511. position: instance.position.asArray(),
  25512. scaling: instance.scaling.asArray()
  25513. };
  25514. if (instance.rotationQuaternion) {
  25515. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  25516. }
  25517. else if (instance.rotation) {
  25518. serializationInstance.rotation = instance.rotation.asArray();
  25519. }
  25520. serializationObject.instances.push(serializationInstance);
  25521. // Animations
  25522. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  25523. serializationInstance.ranges = instance.serializeAnimationRanges();
  25524. }
  25525. //
  25526. // Animations
  25527. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  25528. serializationObject.ranges = this.serializeAnimationRanges();
  25529. // Layer mask
  25530. serializationObject.layerMask = this.layerMask;
  25531. // Alpha
  25532. serializationObject.alphaIndex = this.alphaIndex;
  25533. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  25534. // Overlay
  25535. serializationObject.overlayAlpha = this.overlayAlpha;
  25536. serializationObject.overlayColor = this.overlayColor.asArray();
  25537. serializationObject.renderOverlay = this.renderOverlay;
  25538. // Fog
  25539. serializationObject.applyFog = this.applyFog;
  25540. // Action Manager
  25541. if (this.actionManager) {
  25542. serializationObject.actions = this.actionManager.serialize(this.name);
  25543. }
  25544. };
  25545. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  25546. if (!this.geometry) {
  25547. return;
  25548. }
  25549. this._markSubMeshesAsAttributesDirty();
  25550. var morphTargetManager = this._morphTargetManager;
  25551. if (morphTargetManager && morphTargetManager.vertexCount) {
  25552. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  25553. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  25554. this.morphTargetManager = null;
  25555. return;
  25556. }
  25557. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  25558. var morphTarget = morphTargetManager.getActiveTarget(index);
  25559. var positions = morphTarget.getPositions();
  25560. if (!positions) {
  25561. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  25562. return;
  25563. }
  25564. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  25565. var normals = morphTarget.getNormals();
  25566. if (normals) {
  25567. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  25568. }
  25569. var tangents = morphTarget.getTangents();
  25570. if (tangents) {
  25571. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  25572. }
  25573. }
  25574. }
  25575. else {
  25576. var index = 0;
  25577. // Positions
  25578. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  25579. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  25580. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  25581. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  25582. }
  25583. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  25584. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  25585. }
  25586. index++;
  25587. }
  25588. }
  25589. };
  25590. // Statics
  25591. /**
  25592. * Returns a new Mesh object parsed from the source provided.
  25593. * The parameter `parsedMesh` is the source.
  25594. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  25595. */
  25596. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  25597. var mesh;
  25598. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  25599. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  25600. }
  25601. else {
  25602. mesh = new Mesh(parsedMesh.name, scene);
  25603. }
  25604. mesh.id = parsedMesh.id;
  25605. if (BABYLON.Tags) {
  25606. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  25607. }
  25608. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  25609. if (parsedMesh.metadata !== undefined) {
  25610. mesh.metadata = parsedMesh.metadata;
  25611. }
  25612. if (parsedMesh.rotationQuaternion) {
  25613. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  25614. }
  25615. else if (parsedMesh.rotation) {
  25616. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  25617. }
  25618. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  25619. if (parsedMesh.localMatrix) {
  25620. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  25621. }
  25622. else if (parsedMesh.pivotMatrix) {
  25623. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  25624. }
  25625. mesh.setEnabled(parsedMesh.isEnabled);
  25626. mesh.isVisible = parsedMesh.isVisible;
  25627. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  25628. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  25629. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  25630. if (parsedMesh.applyFog !== undefined) {
  25631. mesh.applyFog = parsedMesh.applyFog;
  25632. }
  25633. if (parsedMesh.pickable !== undefined) {
  25634. mesh.isPickable = parsedMesh.pickable;
  25635. }
  25636. if (parsedMesh.alphaIndex !== undefined) {
  25637. mesh.alphaIndex = parsedMesh.alphaIndex;
  25638. }
  25639. mesh.receiveShadows = parsedMesh.receiveShadows;
  25640. mesh.billboardMode = parsedMesh.billboardMode;
  25641. if (parsedMesh.visibility !== undefined) {
  25642. mesh.visibility = parsedMesh.visibility;
  25643. }
  25644. mesh.checkCollisions = parsedMesh.checkCollisions;
  25645. if (parsedMesh.isBlocker !== undefined) {
  25646. mesh.isBlocker = parsedMesh.isBlocker;
  25647. }
  25648. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  25649. // freezeWorldMatrix
  25650. if (parsedMesh.freezeWorldMatrix) {
  25651. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  25652. }
  25653. // Parent
  25654. if (parsedMesh.parentId) {
  25655. mesh._waitingParentId = parsedMesh.parentId;
  25656. }
  25657. // Actions
  25658. if (parsedMesh.actions !== undefined) {
  25659. mesh._waitingActions = parsedMesh.actions;
  25660. }
  25661. // Overlay
  25662. if (parsedMesh.overlayAlpha !== undefined) {
  25663. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  25664. }
  25665. if (parsedMesh.overlayColor !== undefined) {
  25666. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  25667. }
  25668. if (parsedMesh.renderOverlay !== undefined) {
  25669. mesh.renderOverlay = parsedMesh.renderOverlay;
  25670. }
  25671. // Geometry
  25672. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  25673. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  25674. if (parsedMesh.delayLoadingFile) {
  25675. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  25676. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  25677. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  25678. if (parsedMesh._binaryInfo) {
  25679. mesh._binaryInfo = parsedMesh._binaryInfo;
  25680. }
  25681. mesh._delayInfo = [];
  25682. if (parsedMesh.hasUVs) {
  25683. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  25684. }
  25685. if (parsedMesh.hasUVs2) {
  25686. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  25687. }
  25688. if (parsedMesh.hasUVs3) {
  25689. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  25690. }
  25691. if (parsedMesh.hasUVs4) {
  25692. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  25693. }
  25694. if (parsedMesh.hasUVs5) {
  25695. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  25696. }
  25697. if (parsedMesh.hasUVs6) {
  25698. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  25699. }
  25700. if (parsedMesh.hasColors) {
  25701. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  25702. }
  25703. if (parsedMesh.hasMatricesIndices) {
  25704. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25705. }
  25706. if (parsedMesh.hasMatricesWeights) {
  25707. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25708. }
  25709. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  25710. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  25711. mesh._checkDelayState();
  25712. }
  25713. }
  25714. else {
  25715. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  25716. }
  25717. // Material
  25718. if (parsedMesh.materialId) {
  25719. mesh.setMaterialByID(parsedMesh.materialId);
  25720. }
  25721. else {
  25722. mesh.material = null;
  25723. }
  25724. // Morph targets
  25725. if (parsedMesh.morphTargetManagerId > -1) {
  25726. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  25727. }
  25728. // Skeleton
  25729. if (parsedMesh.skeletonId > -1) {
  25730. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  25731. if (parsedMesh.numBoneInfluencers) {
  25732. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  25733. }
  25734. }
  25735. // Animations
  25736. if (parsedMesh.animations) {
  25737. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  25738. var parsedAnimation = parsedMesh.animations[animationIndex];
  25739. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  25740. }
  25741. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  25742. }
  25743. if (parsedMesh.autoAnimate) {
  25744. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  25745. }
  25746. // Layer Mask
  25747. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  25748. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  25749. }
  25750. else {
  25751. mesh.layerMask = 0x0FFFFFFF;
  25752. }
  25753. // Physics
  25754. if (parsedMesh.physicsImpostor) {
  25755. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  25756. mass: parsedMesh.physicsMass,
  25757. friction: parsedMesh.physicsFriction,
  25758. restitution: parsedMesh.physicsRestitution
  25759. }, scene);
  25760. }
  25761. // Instances
  25762. if (parsedMesh.instances) {
  25763. for (var index = 0; index < parsedMesh.instances.length; index++) {
  25764. var parsedInstance = parsedMesh.instances[index];
  25765. var instance = mesh.createInstance(parsedInstance.name);
  25766. if (parsedInstance.id) {
  25767. instance.id = parsedInstance.id;
  25768. }
  25769. if (BABYLON.Tags) {
  25770. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  25771. }
  25772. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  25773. if (parsedInstance.parentId) {
  25774. instance._waitingParentId = parsedInstance.parentId;
  25775. }
  25776. if (parsedInstance.rotationQuaternion) {
  25777. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  25778. }
  25779. else if (parsedInstance.rotation) {
  25780. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  25781. }
  25782. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  25783. instance.checkCollisions = mesh.checkCollisions;
  25784. if (parsedMesh.animations) {
  25785. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  25786. parsedAnimation = parsedMesh.animations[animationIndex];
  25787. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  25788. }
  25789. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  25790. }
  25791. }
  25792. }
  25793. return mesh;
  25794. };
  25795. /**
  25796. * Creates a ribbon mesh.
  25797. * Please consider using the same method from the MeshBuilder class instead.
  25798. * 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.
  25799. *
  25800. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  25801. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  25802. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  25803. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  25804. * 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.
  25805. * 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.
  25806. * 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
  25807. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25808. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25809. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25810. */
  25811. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  25812. if (closeArray === void 0) { closeArray = false; }
  25813. if (updatable === void 0) { updatable = false; }
  25814. return BABYLON.MeshBuilder.CreateRibbon(name, {
  25815. pathArray: pathArray,
  25816. closeArray: closeArray,
  25817. closePath: closePath,
  25818. offset: offset,
  25819. updatable: updatable,
  25820. sideOrientation: sideOrientation,
  25821. instance: instance
  25822. }, scene);
  25823. };
  25824. /**
  25825. * Creates a plane polygonal mesh. By default, this is a disc.
  25826. * Please consider using the same method from the MeshBuilder class instead.
  25827. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  25828. * 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.
  25829. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25830. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25831. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25832. */
  25833. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  25834. if (scene === void 0) { scene = null; }
  25835. var options = {
  25836. radius: radius,
  25837. tessellation: tessellation,
  25838. sideOrientation: sideOrientation,
  25839. updatable: updatable
  25840. };
  25841. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  25842. };
  25843. /**
  25844. * Creates a box mesh.
  25845. * Please consider using the same method from the MeshBuilder class instead.
  25846. * The parameter `size` sets the size (float) of each box side (default 1).
  25847. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25848. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25849. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25850. */
  25851. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  25852. if (scene === void 0) { scene = null; }
  25853. var options = {
  25854. size: size,
  25855. sideOrientation: sideOrientation,
  25856. updatable: updatable
  25857. };
  25858. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  25859. };
  25860. /**
  25861. * Creates a sphere mesh.
  25862. * Please consider using the same method from the MeshBuilder class instead.
  25863. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  25864. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  25865. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25866. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25867. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25868. */
  25869. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  25870. var options = {
  25871. segments: segments,
  25872. diameterX: diameter,
  25873. diameterY: diameter,
  25874. diameterZ: diameter,
  25875. sideOrientation: sideOrientation,
  25876. updatable: updatable
  25877. };
  25878. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  25879. };
  25880. /**
  25881. * Creates a cylinder or a cone mesh.
  25882. * Please consider using the same method from the MeshBuilder class instead.
  25883. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  25884. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  25885. * 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.
  25886. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  25887. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  25888. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25889. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25890. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25891. */
  25892. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  25893. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  25894. if (scene !== undefined) {
  25895. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  25896. updatable = scene;
  25897. }
  25898. scene = subdivisions;
  25899. subdivisions = 1;
  25900. }
  25901. var options = {
  25902. height: height,
  25903. diameterTop: diameterTop,
  25904. diameterBottom: diameterBottom,
  25905. tessellation: tessellation,
  25906. subdivisions: subdivisions,
  25907. sideOrientation: sideOrientation,
  25908. updatable: updatable
  25909. };
  25910. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  25911. };
  25912. // Torus (Code from SharpDX.org)
  25913. /**
  25914. * Creates a torus mesh.
  25915. * Please consider using the same method from the MeshBuilder class instead.
  25916. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  25917. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  25918. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  25919. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25920. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25921. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25922. */
  25923. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  25924. var options = {
  25925. diameter: diameter,
  25926. thickness: thickness,
  25927. tessellation: tessellation,
  25928. sideOrientation: sideOrientation,
  25929. updatable: updatable
  25930. };
  25931. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  25932. };
  25933. /**
  25934. * Creates a torus knot mesh.
  25935. * Please consider using the same method from the MeshBuilder class instead.
  25936. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  25937. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  25938. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  25939. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  25940. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25941. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25942. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25943. */
  25944. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  25945. var options = {
  25946. radius: radius,
  25947. tube: tube,
  25948. radialSegments: radialSegments,
  25949. tubularSegments: tubularSegments,
  25950. p: p,
  25951. q: q,
  25952. sideOrientation: sideOrientation,
  25953. updatable: updatable
  25954. };
  25955. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  25956. };
  25957. /**
  25958. * Creates a line mesh.
  25959. * Please consider using the same method from the MeshBuilder class instead.
  25960. * 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.
  25961. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  25962. * The parameter `points` is an array successive Vector3.
  25963. * 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
  25964. * When updating an instance, remember that only point positions can change, not the number of points.
  25965. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25966. */
  25967. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  25968. if (scene === void 0) { scene = null; }
  25969. if (updatable === void 0) { updatable = false; }
  25970. if (instance === void 0) { instance = null; }
  25971. var options = {
  25972. points: points,
  25973. updatable: updatable,
  25974. instance: instance
  25975. };
  25976. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  25977. };
  25978. /**
  25979. * Creates a dashed line mesh.
  25980. * Please consider using the same method from the MeshBuilder class instead.
  25981. * 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.
  25982. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  25983. * The parameter `points` is an array successive Vector3.
  25984. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  25985. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  25986. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  25987. * 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
  25988. * When updating an instance, remember that only point positions can change, not the number of points.
  25989. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25990. */
  25991. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  25992. if (scene === void 0) { scene = null; }
  25993. var options = {
  25994. points: points,
  25995. dashSize: dashSize,
  25996. gapSize: gapSize,
  25997. dashNb: dashNb,
  25998. updatable: updatable,
  25999. instance: instance
  26000. };
  26001. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  26002. };
  26003. /**
  26004. * Creates a polygon mesh.
  26005. * Please consider using the same method from the MeshBuilder class instead.
  26006. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  26007. * 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.
  26008. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26009. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26010. * Remember you can only change the shape positions, not their number when updating a polygon.
  26011. */
  26012. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  26013. var options = {
  26014. shape: shape,
  26015. holes: holes,
  26016. updatable: updatable,
  26017. sideOrientation: sideOrientation
  26018. };
  26019. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  26020. };
  26021. /**
  26022. * Creates an extruded polygon mesh, with depth in the Y direction.
  26023. * Please consider using the same method from the MeshBuilder class instead.
  26024. */
  26025. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  26026. var options = {
  26027. shape: shape,
  26028. holes: holes,
  26029. depth: depth,
  26030. updatable: updatable,
  26031. sideOrientation: sideOrientation
  26032. };
  26033. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  26034. };
  26035. /**
  26036. * Creates an extruded shape mesh.
  26037. * 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.
  26038. * Please consider using the same method from the MeshBuilder class instead.
  26039. *
  26040. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  26041. * 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
  26042. * extruded along the Z axis.
  26043. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  26044. * 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.
  26045. * The parameter `scale` (float, default 1) is the value to scale the shape.
  26046. * 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
  26047. * 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
  26048. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  26049. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26050. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26051. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26052. */
  26053. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  26054. if (scene === void 0) { scene = null; }
  26055. var options = {
  26056. shape: shape,
  26057. path: path,
  26058. scale: scale,
  26059. rotation: rotation,
  26060. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  26061. sideOrientation: sideOrientation,
  26062. instance: instance,
  26063. updatable: updatable
  26064. };
  26065. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  26066. };
  26067. /**
  26068. * Creates an custom extruded shape mesh.
  26069. * 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.
  26070. * Please consider using the same method from the MeshBuilder class instead.
  26071. *
  26072. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  26073. * 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
  26074. * extruded along the Z axis.
  26075. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  26076. * 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
  26077. * and the distance of this point from the begining of the path :
  26078. * ```javascript
  26079. * var rotationFunction = function(i, distance) {
  26080. * // do things
  26081. * return rotationValue; }
  26082. * ```
  26083. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  26084. * 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
  26085. * and the distance of this point from the begining of the path :
  26086. * ```javascript
  26087. * var scaleFunction = function(i, distance) {
  26088. * // do things
  26089. * return scaleValue;}
  26090. * ```
  26091. * It must returns a float value that will be the scale value applied to the shape on each path point.
  26092. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  26093. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  26094. * 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
  26095. * 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
  26096. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  26097. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26098. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26099. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26100. */
  26101. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  26102. var options = {
  26103. shape: shape,
  26104. path: path,
  26105. scaleFunction: scaleFunction,
  26106. rotationFunction: rotationFunction,
  26107. ribbonCloseArray: ribbonCloseArray,
  26108. ribbonClosePath: ribbonClosePath,
  26109. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  26110. sideOrientation: sideOrientation,
  26111. instance: instance,
  26112. updatable: updatable
  26113. };
  26114. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  26115. };
  26116. /**
  26117. * Creates lathe mesh.
  26118. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  26119. * Please consider using the same method from the MeshBuilder class instead.
  26120. * 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
  26121. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  26122. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  26123. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  26124. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26125. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26126. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26127. */
  26128. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  26129. var options = {
  26130. shape: shape,
  26131. radius: radius,
  26132. tessellation: tessellation,
  26133. sideOrientation: sideOrientation,
  26134. updatable: updatable
  26135. };
  26136. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  26137. };
  26138. /**
  26139. * Creates a plane mesh.
  26140. * Please consider using the same method from the MeshBuilder class instead.
  26141. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  26142. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26143. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26144. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26145. */
  26146. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  26147. var options = {
  26148. size: size,
  26149. width: size,
  26150. height: size,
  26151. sideOrientation: sideOrientation,
  26152. updatable: updatable
  26153. };
  26154. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  26155. };
  26156. /**
  26157. * Creates a ground mesh.
  26158. * Please consider using the same method from the MeshBuilder class instead.
  26159. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  26160. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  26161. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26162. */
  26163. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  26164. var options = {
  26165. width: width,
  26166. height: height,
  26167. subdivisions: subdivisions,
  26168. updatable: updatable
  26169. };
  26170. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  26171. };
  26172. /**
  26173. * Creates a tiled ground mesh.
  26174. * Please consider using the same method from the MeshBuilder class instead.
  26175. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  26176. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  26177. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  26178. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  26179. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  26180. * numbers of subdivisions on the ground width and height of each tile.
  26181. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26182. */
  26183. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  26184. var options = {
  26185. xmin: xmin,
  26186. zmin: zmin,
  26187. xmax: xmax,
  26188. zmax: zmax,
  26189. subdivisions: subdivisions,
  26190. precision: precision,
  26191. updatable: updatable
  26192. };
  26193. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  26194. };
  26195. /**
  26196. * Creates a ground mesh from a height map.
  26197. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  26198. * Please consider using the same method from the MeshBuilder class instead.
  26199. * The parameter `url` sets the URL of the height map image resource.
  26200. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  26201. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  26202. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  26203. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  26204. * 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).
  26205. * This function is passed the newly built mesh :
  26206. * ```javascript
  26207. * function(mesh) { // do things
  26208. * return; }
  26209. * ```
  26210. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26211. */
  26212. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  26213. var options = {
  26214. width: width,
  26215. height: height,
  26216. subdivisions: subdivisions,
  26217. minHeight: minHeight,
  26218. maxHeight: maxHeight,
  26219. updatable: updatable,
  26220. onReady: onReady
  26221. };
  26222. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  26223. };
  26224. /**
  26225. * Creates a tube mesh.
  26226. * 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.
  26227. * Please consider using the same method from the MeshBuilder class instead.
  26228. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  26229. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  26230. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  26231. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  26232. * 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.
  26233. * It must return a radius value (positive float) :
  26234. * ```javascript
  26235. * var radiusFunction = function(i, distance) {
  26236. * // do things
  26237. * return radius; }
  26238. * ```
  26239. * 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
  26240. * 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
  26241. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26242. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26243. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26244. */
  26245. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  26246. var options = {
  26247. path: path,
  26248. radius: radius,
  26249. tessellation: tessellation,
  26250. radiusFunction: radiusFunction,
  26251. arc: 1,
  26252. cap: cap,
  26253. updatable: updatable,
  26254. sideOrientation: sideOrientation,
  26255. instance: instance
  26256. };
  26257. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  26258. };
  26259. /**
  26260. * Creates a polyhedron mesh.
  26261. * Please consider using the same method from the MeshBuilder class instead.
  26262. * 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
  26263. * to choose the wanted type.
  26264. * The parameter `size` (positive float, default 1) sets the polygon size.
  26265. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  26266. * 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`.
  26267. * 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
  26268. * 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)`).
  26269. * 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
  26270. * 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.
  26271. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26272. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26273. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26274. */
  26275. Mesh.CreatePolyhedron = function (name, options, scene) {
  26276. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  26277. };
  26278. /**
  26279. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  26280. * Please consider using the same method from the MeshBuilder class instead.
  26281. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  26282. * 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`).
  26283. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  26284. * 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.
  26285. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26286. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26287. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26288. */
  26289. Mesh.CreateIcoSphere = function (name, options, scene) {
  26290. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  26291. };
  26292. /**
  26293. * Creates a decal mesh.
  26294. * Please consider using the same method from the MeshBuilder class instead.
  26295. * 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.
  26296. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  26297. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  26298. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  26299. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  26300. */
  26301. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  26302. var options = {
  26303. position: position,
  26304. normal: normal,
  26305. size: size,
  26306. angle: angle
  26307. };
  26308. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  26309. };
  26310. // Skeletons
  26311. /**
  26312. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  26313. */
  26314. Mesh.prototype.setPositionsForCPUSkinning = function () {
  26315. if (!this._sourcePositions) {
  26316. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26317. if (!source) {
  26318. return this._sourcePositions;
  26319. }
  26320. this._sourcePositions = new Float32Array(source);
  26321. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  26322. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  26323. }
  26324. }
  26325. return this._sourcePositions;
  26326. };
  26327. /**
  26328. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  26329. */
  26330. Mesh.prototype.setNormalsForCPUSkinning = function () {
  26331. if (!this._sourceNormals) {
  26332. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26333. if (!source) {
  26334. return this._sourceNormals;
  26335. }
  26336. this._sourceNormals = new Float32Array(source);
  26337. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  26338. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  26339. }
  26340. }
  26341. return this._sourceNormals;
  26342. };
  26343. /**
  26344. * Updates the vertex buffer by applying transformation from the bones.
  26345. * Returns the Mesh.
  26346. *
  26347. * @param {skeleton} skeleton to apply
  26348. */
  26349. Mesh.prototype.applySkeleton = function (skeleton) {
  26350. if (!this.geometry) {
  26351. return this;
  26352. }
  26353. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  26354. return this;
  26355. }
  26356. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  26357. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26358. return this;
  26359. }
  26360. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26361. return this;
  26362. }
  26363. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26364. return this;
  26365. }
  26366. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26367. return this;
  26368. }
  26369. if (!this._sourcePositions) {
  26370. var submeshes = this.subMeshes.slice();
  26371. this.setPositionsForCPUSkinning();
  26372. this.subMeshes = submeshes;
  26373. }
  26374. if (!this._sourceNormals) {
  26375. this.setNormalsForCPUSkinning();
  26376. }
  26377. // positionsData checks for not being Float32Array will only pass at most once
  26378. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26379. if (!positionsData) {
  26380. return this;
  26381. }
  26382. if (!(positionsData instanceof Float32Array)) {
  26383. positionsData = new Float32Array(positionsData);
  26384. }
  26385. // normalsData checks for not being Float32Array will only pass at most once
  26386. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26387. if (!normalsData) {
  26388. return this;
  26389. }
  26390. if (!(normalsData instanceof Float32Array)) {
  26391. normalsData = new Float32Array(normalsData);
  26392. }
  26393. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  26394. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  26395. if (!matricesWeightsData || !matricesIndicesData) {
  26396. return this;
  26397. }
  26398. var needExtras = this.numBoneInfluencers > 4;
  26399. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  26400. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  26401. var skeletonMatrices = skeleton.getTransformMatrices(this);
  26402. var tempVector3 = BABYLON.Vector3.Zero();
  26403. var finalMatrix = new BABYLON.Matrix();
  26404. var tempMatrix = new BABYLON.Matrix();
  26405. var matWeightIdx = 0;
  26406. var inf;
  26407. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  26408. var weight;
  26409. for (inf = 0; inf < 4; inf++) {
  26410. weight = matricesWeightsData[matWeightIdx + inf];
  26411. if (weight > 0) {
  26412. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  26413. finalMatrix.addToSelf(tempMatrix);
  26414. }
  26415. else
  26416. break;
  26417. }
  26418. if (needExtras) {
  26419. for (inf = 0; inf < 4; inf++) {
  26420. weight = matricesWeightsExtraData[matWeightIdx + inf];
  26421. if (weight > 0) {
  26422. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  26423. finalMatrix.addToSelf(tempMatrix);
  26424. }
  26425. else
  26426. break;
  26427. }
  26428. }
  26429. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  26430. tempVector3.toArray(positionsData, index);
  26431. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  26432. tempVector3.toArray(normalsData, index);
  26433. finalMatrix.reset();
  26434. }
  26435. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  26436. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  26437. return this;
  26438. };
  26439. // Tools
  26440. /**
  26441. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  26442. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  26443. */
  26444. Mesh.MinMax = function (meshes) {
  26445. var minVector = null;
  26446. var maxVector = null;
  26447. meshes.forEach(function (mesh, index, array) {
  26448. var boundingInfo = mesh.getBoundingInfo();
  26449. var boundingBox = boundingInfo.boundingBox;
  26450. if (!minVector || !maxVector) {
  26451. minVector = boundingBox.minimumWorld;
  26452. maxVector = boundingBox.maximumWorld;
  26453. }
  26454. else {
  26455. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  26456. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  26457. }
  26458. });
  26459. if (!minVector || !maxVector) {
  26460. return {
  26461. min: BABYLON.Vector3.Zero(),
  26462. max: BABYLON.Vector3.Zero()
  26463. };
  26464. }
  26465. return {
  26466. min: minVector,
  26467. max: maxVector
  26468. };
  26469. };
  26470. /**
  26471. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  26472. */
  26473. Mesh.Center = function (meshesOrMinMaxVector) {
  26474. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  26475. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  26476. };
  26477. /**
  26478. * Merge the array of meshes into a single mesh for performance reasons.
  26479. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  26480. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  26481. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  26482. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  26483. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  26484. */
  26485. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  26486. if (disposeSource === void 0) { disposeSource = true; }
  26487. var index;
  26488. if (!allow32BitsIndices) {
  26489. var totalVertices = 0;
  26490. // Counting vertices
  26491. for (index = 0; index < meshes.length; index++) {
  26492. if (meshes[index]) {
  26493. totalVertices += meshes[index].getTotalVertices();
  26494. if (totalVertices > 65536) {
  26495. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  26496. return null;
  26497. }
  26498. }
  26499. }
  26500. }
  26501. // Merge
  26502. var vertexData = null;
  26503. var otherVertexData;
  26504. var indiceArray = new Array();
  26505. var source = null;
  26506. for (index = 0; index < meshes.length; index++) {
  26507. if (meshes[index]) {
  26508. meshes[index].computeWorldMatrix(true);
  26509. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  26510. otherVertexData.transform(meshes[index].getWorldMatrix());
  26511. if (vertexData) {
  26512. vertexData.merge(otherVertexData);
  26513. }
  26514. else {
  26515. vertexData = otherVertexData;
  26516. source = meshes[index];
  26517. }
  26518. if (subdivideWithSubMeshes) {
  26519. indiceArray.push(meshes[index].getTotalIndices());
  26520. }
  26521. }
  26522. }
  26523. source = source;
  26524. if (!meshSubclass) {
  26525. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  26526. }
  26527. vertexData.applyToMesh(meshSubclass);
  26528. // Setting properties
  26529. meshSubclass.material = source.material;
  26530. meshSubclass.checkCollisions = source.checkCollisions;
  26531. // Cleaning
  26532. if (disposeSource) {
  26533. for (index = 0; index < meshes.length; index++) {
  26534. if (meshes[index]) {
  26535. meshes[index].dispose();
  26536. }
  26537. }
  26538. }
  26539. // Subdivide
  26540. if (subdivideWithSubMeshes) {
  26541. //-- Suppresions du submesh global
  26542. meshSubclass.releaseSubMeshes();
  26543. index = 0;
  26544. var offset = 0;
  26545. //-- aplique la subdivision en fonction du tableau d'indices
  26546. while (index < indiceArray.length) {
  26547. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  26548. offset += indiceArray[index];
  26549. index++;
  26550. }
  26551. }
  26552. return meshSubclass;
  26553. };
  26554. // Consts
  26555. Mesh._FRONTSIDE = 0;
  26556. Mesh._BACKSIDE = 1;
  26557. Mesh._DOUBLESIDE = 2;
  26558. Mesh._DEFAULTSIDE = 0;
  26559. Mesh._NO_CAP = 0;
  26560. Mesh._CAP_START = 1;
  26561. Mesh._CAP_END = 2;
  26562. Mesh._CAP_ALL = 3;
  26563. return Mesh;
  26564. }(BABYLON.AbstractMesh));
  26565. BABYLON.Mesh = Mesh;
  26566. })(BABYLON || (BABYLON = {}));
  26567. //# sourceMappingURL=babylon.mesh.js.map
  26568. var BABYLON;
  26569. (function (BABYLON) {
  26570. var BaseSubMesh = /** @class */ (function () {
  26571. function BaseSubMesh() {
  26572. }
  26573. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  26574. get: function () {
  26575. return this._materialEffect;
  26576. },
  26577. enumerable: true,
  26578. configurable: true
  26579. });
  26580. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  26581. if (defines === void 0) { defines = null; }
  26582. if (this._materialEffect === effect) {
  26583. if (!effect) {
  26584. this._materialDefines = null;
  26585. }
  26586. return;
  26587. }
  26588. this._materialDefines = defines;
  26589. this._materialEffect = effect;
  26590. };
  26591. return BaseSubMesh;
  26592. }());
  26593. BABYLON.BaseSubMesh = BaseSubMesh;
  26594. var SubMesh = /** @class */ (function (_super) {
  26595. __extends(SubMesh, _super);
  26596. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  26597. if (createBoundingBox === void 0) { createBoundingBox = true; }
  26598. var _this = _super.call(this) || this;
  26599. _this.materialIndex = materialIndex;
  26600. _this.verticesStart = verticesStart;
  26601. _this.verticesCount = verticesCount;
  26602. _this.indexStart = indexStart;
  26603. _this.indexCount = indexCount;
  26604. _this._renderId = 0;
  26605. _this._mesh = mesh;
  26606. _this._renderingMesh = renderingMesh || mesh;
  26607. mesh.subMeshes.push(_this);
  26608. _this._trianglePlanes = [];
  26609. _this._id = mesh.subMeshes.length - 1;
  26610. if (createBoundingBox) {
  26611. _this.refreshBoundingInfo();
  26612. mesh.computeWorldMatrix(true);
  26613. }
  26614. return _this;
  26615. }
  26616. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  26617. if (createBoundingBox === void 0) { createBoundingBox = true; }
  26618. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  26619. };
  26620. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  26621. get: function () {
  26622. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  26623. },
  26624. enumerable: true,
  26625. configurable: true
  26626. });
  26627. /**
  26628. * Returns the submesh BoudingInfo object.
  26629. */
  26630. SubMesh.prototype.getBoundingInfo = function () {
  26631. if (this.IsGlobal) {
  26632. return this._mesh.getBoundingInfo();
  26633. }
  26634. return this._boundingInfo;
  26635. };
  26636. /**
  26637. * Sets the submesh BoundingInfo.
  26638. * Return the SubMesh.
  26639. */
  26640. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  26641. this._boundingInfo = boundingInfo;
  26642. return this;
  26643. };
  26644. /**
  26645. * Returns the mesh of the current submesh.
  26646. */
  26647. SubMesh.prototype.getMesh = function () {
  26648. return this._mesh;
  26649. };
  26650. /**
  26651. * Returns the rendering mesh of the submesh.
  26652. */
  26653. SubMesh.prototype.getRenderingMesh = function () {
  26654. return this._renderingMesh;
  26655. };
  26656. /**
  26657. * Returns the submesh material.
  26658. */
  26659. SubMesh.prototype.getMaterial = function () {
  26660. var rootMaterial = this._renderingMesh.material;
  26661. if (rootMaterial === null || rootMaterial === undefined) {
  26662. return this._mesh.getScene().defaultMaterial;
  26663. }
  26664. else if (rootMaterial.getSubMaterial) {
  26665. var multiMaterial = rootMaterial;
  26666. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  26667. if (this._currentMaterial !== effectiveMaterial) {
  26668. this._currentMaterial = effectiveMaterial;
  26669. this._materialDefines = null;
  26670. }
  26671. return effectiveMaterial;
  26672. }
  26673. return rootMaterial;
  26674. };
  26675. // Methods
  26676. /**
  26677. * Sets a new updated BoundingInfo object to the submesh.
  26678. * Returns the SubMesh.
  26679. */
  26680. SubMesh.prototype.refreshBoundingInfo = function () {
  26681. this._lastColliderWorldVertices = null;
  26682. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  26683. return this;
  26684. }
  26685. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26686. if (!data) {
  26687. this._boundingInfo = this._mesh.getBoundingInfo();
  26688. return this;
  26689. }
  26690. var indices = this._renderingMesh.getIndices();
  26691. var extend;
  26692. //is this the only submesh?
  26693. if (this.indexStart === 0 && this.indexCount === indices.length) {
  26694. var boundingInfo = this._renderingMesh.getBoundingInfo();
  26695. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  26696. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  26697. }
  26698. else {
  26699. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  26700. }
  26701. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  26702. return this;
  26703. };
  26704. SubMesh.prototype._checkCollision = function (collider) {
  26705. var boundingInfo = this._renderingMesh.getBoundingInfo();
  26706. return boundingInfo._checkCollision(collider);
  26707. };
  26708. /**
  26709. * Updates the submesh BoundingInfo.
  26710. * Returns the Submesh.
  26711. */
  26712. SubMesh.prototype.updateBoundingInfo = function (world) {
  26713. var boundingInfo = this.getBoundingInfo();
  26714. if (!boundingInfo) {
  26715. this.refreshBoundingInfo();
  26716. boundingInfo = this.getBoundingInfo();
  26717. }
  26718. boundingInfo.update(world);
  26719. return this;
  26720. };
  26721. /**
  26722. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  26723. * Boolean returned.
  26724. */
  26725. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  26726. var boundingInfo = this.getBoundingInfo();
  26727. if (!boundingInfo) {
  26728. return false;
  26729. }
  26730. return boundingInfo.isInFrustum(frustumPlanes);
  26731. };
  26732. /**
  26733. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  26734. * Boolean returned.
  26735. */
  26736. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  26737. var boundingInfo = this.getBoundingInfo();
  26738. if (!boundingInfo) {
  26739. return false;
  26740. }
  26741. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  26742. };
  26743. /**
  26744. * Renders the submesh.
  26745. * Returns it.
  26746. */
  26747. SubMesh.prototype.render = function (enableAlphaMode) {
  26748. this._renderingMesh.render(this, enableAlphaMode);
  26749. return this;
  26750. };
  26751. /**
  26752. * Returns a new Index Buffer.
  26753. * Type returned : WebGLBuffer.
  26754. */
  26755. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  26756. if (!this._linesIndexBuffer) {
  26757. var linesIndices = [];
  26758. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  26759. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  26760. }
  26761. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  26762. this.linesIndexCount = linesIndices.length;
  26763. }
  26764. return this._linesIndexBuffer;
  26765. };
  26766. /**
  26767. * True is the passed Ray intersects the submesh bounding box.
  26768. * Boolean returned.
  26769. */
  26770. SubMesh.prototype.canIntersects = function (ray) {
  26771. var boundingInfo = this.getBoundingInfo();
  26772. if (!boundingInfo) {
  26773. return false;
  26774. }
  26775. return ray.intersectsBox(boundingInfo.boundingBox);
  26776. };
  26777. /**
  26778. * Returns an object IntersectionInfo.
  26779. */
  26780. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  26781. var intersectInfo = null;
  26782. // LineMesh first as it's also a Mesh...
  26783. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  26784. var lineMesh = this._mesh;
  26785. // Line test
  26786. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  26787. var p0 = positions[indices[index]];
  26788. var p1 = positions[indices[index + 1]];
  26789. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  26790. if (length < 0) {
  26791. continue;
  26792. }
  26793. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  26794. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  26795. if (fastCheck) {
  26796. break;
  26797. }
  26798. }
  26799. }
  26800. }
  26801. else {
  26802. // Triangles test
  26803. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  26804. var p0 = positions[indices[index]];
  26805. var p1 = positions[indices[index + 1]];
  26806. var p2 = positions[indices[index + 2]];
  26807. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  26808. if (currentIntersectInfo) {
  26809. if (currentIntersectInfo.distance < 0) {
  26810. continue;
  26811. }
  26812. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  26813. intersectInfo = currentIntersectInfo;
  26814. intersectInfo.faceId = index / 3;
  26815. if (fastCheck) {
  26816. break;
  26817. }
  26818. }
  26819. }
  26820. }
  26821. }
  26822. return intersectInfo;
  26823. };
  26824. SubMesh.prototype._rebuild = function () {
  26825. if (this._linesIndexBuffer) {
  26826. this._linesIndexBuffer = null;
  26827. }
  26828. };
  26829. // Clone
  26830. /**
  26831. * Creates a new Submesh from the passed Mesh.
  26832. */
  26833. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  26834. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  26835. if (!this.IsGlobal) {
  26836. var boundingInfo = this.getBoundingInfo();
  26837. if (!boundingInfo) {
  26838. return result;
  26839. }
  26840. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  26841. }
  26842. return result;
  26843. };
  26844. // Dispose
  26845. /**
  26846. * Disposes the Submesh.
  26847. * Returns nothing.
  26848. */
  26849. SubMesh.prototype.dispose = function () {
  26850. if (this._linesIndexBuffer) {
  26851. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  26852. this._linesIndexBuffer = null;
  26853. }
  26854. // Remove from mesh
  26855. var index = this._mesh.subMeshes.indexOf(this);
  26856. this._mesh.subMeshes.splice(index, 1);
  26857. };
  26858. // Statics
  26859. /**
  26860. * Creates a new Submesh from the passed parameters :
  26861. * - materialIndex (integer) : the index of the main mesh material.
  26862. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  26863. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  26864. * - mesh (Mesh) : the main mesh to create the submesh from.
  26865. * - renderingMesh (optional Mesh) : rendering mesh.
  26866. */
  26867. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  26868. var minVertexIndex = Number.MAX_VALUE;
  26869. var maxVertexIndex = -Number.MAX_VALUE;
  26870. renderingMesh = (renderingMesh || mesh);
  26871. var indices = renderingMesh.getIndices();
  26872. for (var index = startIndex; index < startIndex + indexCount; index++) {
  26873. var vertexIndex = indices[index];
  26874. if (vertexIndex < minVertexIndex)
  26875. minVertexIndex = vertexIndex;
  26876. if (vertexIndex > maxVertexIndex)
  26877. maxVertexIndex = vertexIndex;
  26878. }
  26879. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  26880. };
  26881. return SubMesh;
  26882. }(BaseSubMesh));
  26883. BABYLON.SubMesh = SubMesh;
  26884. })(BABYLON || (BABYLON = {}));
  26885. //# sourceMappingURL=babylon.subMesh.js.map
  26886. var BABYLON;
  26887. (function (BABYLON) {
  26888. var EffectFallbacks = /** @class */ (function () {
  26889. function EffectFallbacks() {
  26890. this._defines = {};
  26891. this._currentRank = 32;
  26892. this._maxRank = -1;
  26893. }
  26894. EffectFallbacks.prototype.unBindMesh = function () {
  26895. this._mesh = null;
  26896. };
  26897. EffectFallbacks.prototype.addFallback = function (rank, define) {
  26898. if (!this._defines[rank]) {
  26899. if (rank < this._currentRank) {
  26900. this._currentRank = rank;
  26901. }
  26902. if (rank > this._maxRank) {
  26903. this._maxRank = rank;
  26904. }
  26905. this._defines[rank] = new Array();
  26906. }
  26907. this._defines[rank].push(define);
  26908. };
  26909. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  26910. this._mesh = mesh;
  26911. if (rank < this._currentRank) {
  26912. this._currentRank = rank;
  26913. }
  26914. if (rank > this._maxRank) {
  26915. this._maxRank = rank;
  26916. }
  26917. };
  26918. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  26919. get: function () {
  26920. return this._currentRank <= this._maxRank;
  26921. },
  26922. enumerable: true,
  26923. configurable: true
  26924. });
  26925. EffectFallbacks.prototype.reduce = function (currentDefines) {
  26926. // First we try to switch to CPU skinning
  26927. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  26928. this._mesh.computeBonesUsingShaders = false;
  26929. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  26930. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  26931. var scene = this._mesh.getScene();
  26932. for (var index = 0; index < scene.meshes.length; index++) {
  26933. var otherMesh = scene.meshes[index];
  26934. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  26935. otherMesh.computeBonesUsingShaders = false;
  26936. }
  26937. }
  26938. }
  26939. else {
  26940. var currentFallbacks = this._defines[this._currentRank];
  26941. if (currentFallbacks) {
  26942. for (var index = 0; index < currentFallbacks.length; index++) {
  26943. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  26944. }
  26945. }
  26946. this._currentRank++;
  26947. }
  26948. return currentDefines;
  26949. };
  26950. return EffectFallbacks;
  26951. }());
  26952. BABYLON.EffectFallbacks = EffectFallbacks;
  26953. var EffectCreationOptions = /** @class */ (function () {
  26954. function EffectCreationOptions() {
  26955. }
  26956. return EffectCreationOptions;
  26957. }());
  26958. BABYLON.EffectCreationOptions = EffectCreationOptions;
  26959. var Effect = /** @class */ (function () {
  26960. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  26961. if (samplers === void 0) { samplers = null; }
  26962. if (defines === void 0) { defines = null; }
  26963. if (fallbacks === void 0) { fallbacks = null; }
  26964. if (onCompiled === void 0) { onCompiled = null; }
  26965. if (onError === void 0) { onError = null; }
  26966. var _this = this;
  26967. this.uniqueId = 0;
  26968. this.onCompileObservable = new BABYLON.Observable();
  26969. this.onErrorObservable = new BABYLON.Observable();
  26970. this.onBindObservable = new BABYLON.Observable();
  26971. this._uniformBuffersNames = {};
  26972. this._isReady = false;
  26973. this._compilationError = "";
  26974. this.name = baseName;
  26975. if (attributesNamesOrOptions.attributes) {
  26976. var options = attributesNamesOrOptions;
  26977. this._engine = uniformsNamesOrEngine;
  26978. this._attributesNames = options.attributes;
  26979. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  26980. this._samplers = options.samplers;
  26981. this.defines = options.defines;
  26982. this.onError = options.onError;
  26983. this.onCompiled = options.onCompiled;
  26984. this._fallbacks = options.fallbacks;
  26985. this._indexParameters = options.indexParameters;
  26986. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  26987. if (options.uniformBuffersNames) {
  26988. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  26989. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  26990. }
  26991. }
  26992. }
  26993. else {
  26994. this._engine = engine;
  26995. this.defines = defines;
  26996. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  26997. this._samplers = samplers;
  26998. this._attributesNames = attributesNamesOrOptions;
  26999. this.onError = onError;
  27000. this.onCompiled = onCompiled;
  27001. this._indexParameters = indexParameters;
  27002. this._fallbacks = fallbacks;
  27003. }
  27004. this.uniqueId = Effect._uniqueIdSeed++;
  27005. var vertexSource;
  27006. var fragmentSource;
  27007. if (baseName.vertexElement) {
  27008. vertexSource = document.getElementById(baseName.vertexElement);
  27009. if (!vertexSource) {
  27010. vertexSource = baseName.vertexElement;
  27011. }
  27012. }
  27013. else {
  27014. vertexSource = baseName.vertex || baseName;
  27015. }
  27016. if (baseName.fragmentElement) {
  27017. fragmentSource = document.getElementById(baseName.fragmentElement);
  27018. if (!fragmentSource) {
  27019. fragmentSource = baseName.fragmentElement;
  27020. }
  27021. }
  27022. else {
  27023. fragmentSource = baseName.fragment || baseName;
  27024. }
  27025. this._loadVertexShader(vertexSource, function (vertexCode) {
  27026. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  27027. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  27028. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  27029. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  27030. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  27031. if (baseName) {
  27032. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  27033. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  27034. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  27035. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  27036. }
  27037. else {
  27038. _this._vertexSourceCode = migratedVertexCode;
  27039. _this._fragmentSourceCode = migratedFragmentCode;
  27040. }
  27041. _this._prepareEffect();
  27042. });
  27043. });
  27044. });
  27045. });
  27046. });
  27047. });
  27048. }
  27049. Object.defineProperty(Effect.prototype, "key", {
  27050. get: function () {
  27051. return this._key;
  27052. },
  27053. enumerable: true,
  27054. configurable: true
  27055. });
  27056. // Properties
  27057. Effect.prototype.isReady = function () {
  27058. return this._isReady;
  27059. };
  27060. Effect.prototype.getEngine = function () {
  27061. return this._engine;
  27062. };
  27063. Effect.prototype.getProgram = function () {
  27064. return this._program;
  27065. };
  27066. Effect.prototype.getAttributesNames = function () {
  27067. return this._attributesNames;
  27068. };
  27069. Effect.prototype.getAttributeLocation = function (index) {
  27070. return this._attributes[index];
  27071. };
  27072. Effect.prototype.getAttributeLocationByName = function (name) {
  27073. var index = this._attributesNames.indexOf(name);
  27074. return this._attributes[index];
  27075. };
  27076. Effect.prototype.getAttributesCount = function () {
  27077. return this._attributes.length;
  27078. };
  27079. Effect.prototype.getUniformIndex = function (uniformName) {
  27080. return this._uniformsNames.indexOf(uniformName);
  27081. };
  27082. Effect.prototype.getUniform = function (uniformName) {
  27083. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  27084. };
  27085. Effect.prototype.getSamplers = function () {
  27086. return this._samplers;
  27087. };
  27088. Effect.prototype.getCompilationError = function () {
  27089. return this._compilationError;
  27090. };
  27091. // Methods
  27092. Effect.prototype.executeWhenCompiled = function (func) {
  27093. if (this.isReady()) {
  27094. func(this);
  27095. return;
  27096. }
  27097. this.onCompileObservable.add(function (effect) {
  27098. func(effect);
  27099. });
  27100. };
  27101. Effect.prototype._loadVertexShader = function (vertex, callback) {
  27102. if (BABYLON.Tools.IsWindowObjectExist()) {
  27103. // DOM element ?
  27104. if (vertex instanceof HTMLElement) {
  27105. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  27106. callback(vertexCode);
  27107. return;
  27108. }
  27109. }
  27110. // Base64 encoded ?
  27111. if (vertex.substr(0, 7) === "base64:") {
  27112. var vertexBinary = window.atob(vertex.substr(7));
  27113. callback(vertexBinary);
  27114. return;
  27115. }
  27116. // Is in local store ?
  27117. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  27118. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  27119. return;
  27120. }
  27121. var vertexShaderUrl;
  27122. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  27123. vertexShaderUrl = vertex;
  27124. }
  27125. else {
  27126. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  27127. }
  27128. // Vertex shader
  27129. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  27130. };
  27131. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  27132. if (BABYLON.Tools.IsWindowObjectExist()) {
  27133. // DOM element ?
  27134. if (fragment instanceof HTMLElement) {
  27135. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  27136. callback(fragmentCode);
  27137. return;
  27138. }
  27139. }
  27140. // Base64 encoded ?
  27141. if (fragment.substr(0, 7) === "base64:") {
  27142. var fragmentBinary = window.atob(fragment.substr(7));
  27143. callback(fragmentBinary);
  27144. return;
  27145. }
  27146. // Is in local store ?
  27147. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  27148. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  27149. return;
  27150. }
  27151. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  27152. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  27153. return;
  27154. }
  27155. var fragmentShaderUrl;
  27156. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  27157. fragmentShaderUrl = fragment;
  27158. }
  27159. else {
  27160. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  27161. }
  27162. // Fragment shader
  27163. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  27164. };
  27165. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  27166. // Rebuild shaders source code
  27167. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  27168. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  27169. vertexCode = prefix + vertexCode;
  27170. fragmentCode = prefix + fragmentCode;
  27171. // Number lines of shaders source code
  27172. var i = 2;
  27173. var regex = /\n/gm;
  27174. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  27175. i = 2;
  27176. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  27177. // Dump shaders name and formatted source code
  27178. if (this.name.vertexElement) {
  27179. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  27180. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  27181. }
  27182. else if (this.name.vertex) {
  27183. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  27184. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  27185. }
  27186. else {
  27187. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  27188. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  27189. }
  27190. };
  27191. ;
  27192. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  27193. var preparedSourceCode = this._processPrecision(sourceCode);
  27194. if (this._engine.webGLVersion == 1) {
  27195. callback(preparedSourceCode);
  27196. return;
  27197. }
  27198. // Already converted
  27199. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  27200. callback(preparedSourceCode.replace("#version 300 es", ""));
  27201. return;
  27202. }
  27203. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  27204. // Remove extensions
  27205. // #extension GL_OES_standard_derivatives : enable
  27206. // #extension GL_EXT_shader_texture_lod : enable
  27207. // #extension GL_EXT_frag_depth : enable
  27208. // #extension GL_EXT_draw_buffers : require
  27209. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  27210. var result = preparedSourceCode.replace(regex, "");
  27211. // Migrate to GLSL v300
  27212. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  27213. result = result.replace(/attribute[ \t]/g, "in ");
  27214. result = result.replace(/[ \t]attribute/g, " in");
  27215. if (isFragment) {
  27216. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  27217. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  27218. result = result.replace(/texture2D\s*\(/g, "texture(");
  27219. result = result.replace(/textureCube\s*\(/g, "texture(");
  27220. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  27221. result = result.replace(/gl_FragColor/g, "glFragColor");
  27222. result = result.replace(/gl_FragData/g, "glFragData");
  27223. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  27224. }
  27225. callback(result);
  27226. };
  27227. Effect.prototype._processIncludes = function (sourceCode, callback) {
  27228. var _this = this;
  27229. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  27230. var match = regex.exec(sourceCode);
  27231. var returnValue = new String(sourceCode);
  27232. while (match != null) {
  27233. var includeFile = match[1];
  27234. // Uniform declaration
  27235. if (includeFile.indexOf("__decl__") !== -1) {
  27236. includeFile = includeFile.replace(/__decl__/, "");
  27237. if (this._engine.supportsUniformBuffers) {
  27238. includeFile = includeFile.replace(/Vertex/, "Ubo");
  27239. includeFile = includeFile.replace(/Fragment/, "Ubo");
  27240. }
  27241. includeFile = includeFile + "Declaration";
  27242. }
  27243. if (Effect.IncludesShadersStore[includeFile]) {
  27244. // Substitution
  27245. var includeContent = Effect.IncludesShadersStore[includeFile];
  27246. if (match[2]) {
  27247. var splits = match[3].split(",");
  27248. for (var index = 0; index < splits.length; index += 2) {
  27249. var source = new RegExp(splits[index], "g");
  27250. var dest = splits[index + 1];
  27251. includeContent = includeContent.replace(source, dest);
  27252. }
  27253. }
  27254. if (match[4]) {
  27255. var indexString = match[5];
  27256. if (indexString.indexOf("..") !== -1) {
  27257. var indexSplits = indexString.split("..");
  27258. var minIndex = parseInt(indexSplits[0]);
  27259. var maxIndex = parseInt(indexSplits[1]);
  27260. var sourceIncludeContent = includeContent.slice(0);
  27261. includeContent = "";
  27262. if (isNaN(maxIndex)) {
  27263. maxIndex = this._indexParameters[indexSplits[1]];
  27264. }
  27265. for (var i = minIndex; i < maxIndex; i++) {
  27266. if (!this._engine.supportsUniformBuffers) {
  27267. // Ubo replacement
  27268. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  27269. return p1 + "{X}";
  27270. });
  27271. }
  27272. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  27273. }
  27274. }
  27275. else {
  27276. if (!this._engine.supportsUniformBuffers) {
  27277. // Ubo replacement
  27278. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  27279. return p1 + "{X}";
  27280. });
  27281. }
  27282. includeContent = includeContent.replace(/\{X\}/g, indexString);
  27283. }
  27284. }
  27285. // Replace
  27286. returnValue = returnValue.replace(match[0], includeContent);
  27287. }
  27288. else {
  27289. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  27290. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  27291. Effect.IncludesShadersStore[includeFile] = fileContent;
  27292. _this._processIncludes(returnValue, callback);
  27293. });
  27294. return;
  27295. }
  27296. match = regex.exec(sourceCode);
  27297. }
  27298. callback(returnValue);
  27299. };
  27300. Effect.prototype._processPrecision = function (source) {
  27301. if (source.indexOf("precision highp float") === -1) {
  27302. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  27303. source = "precision mediump float;\n" + source;
  27304. }
  27305. else {
  27306. source = "precision highp float;\n" + source;
  27307. }
  27308. }
  27309. else {
  27310. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  27311. source = source.replace("precision highp float", "precision mediump float");
  27312. }
  27313. }
  27314. return source;
  27315. };
  27316. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  27317. var _this = this;
  27318. this._isReady = false;
  27319. this._vertexSourceCodeOverride = vertexSourceCode;
  27320. this._fragmentSourceCodeOverride = fragmentSourceCode;
  27321. this.onError = function (effect, error) {
  27322. if (onError) {
  27323. onError(error);
  27324. }
  27325. };
  27326. this.onCompiled = function () {
  27327. var scenes = _this.getEngine().scenes;
  27328. for (var i = 0; i < scenes.length; i++) {
  27329. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27330. }
  27331. if (onCompiled) {
  27332. onCompiled(_this._program);
  27333. }
  27334. };
  27335. this._fallbacks = null;
  27336. this._prepareEffect();
  27337. };
  27338. Effect.prototype.getSpecificUniformLocations = function (names) {
  27339. var engine = this._engine;
  27340. return engine.getUniforms(this._program, names);
  27341. };
  27342. Effect.prototype._prepareEffect = function () {
  27343. var attributesNames = this._attributesNames;
  27344. var defines = this.defines;
  27345. var fallbacks = this._fallbacks;
  27346. this._valueCache = {};
  27347. var previousProgram = this._program;
  27348. try {
  27349. var engine = this._engine;
  27350. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  27351. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  27352. }
  27353. else {
  27354. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  27355. }
  27356. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  27357. if (engine.supportsUniformBuffers) {
  27358. for (var name in this._uniformBuffersNames) {
  27359. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  27360. }
  27361. }
  27362. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  27363. this._attributes = engine.getAttributes(this._program, attributesNames);
  27364. var index;
  27365. for (index = 0; index < this._samplers.length; index++) {
  27366. var sampler = this.getUniform(this._samplers[index]);
  27367. if (sampler == null) {
  27368. this._samplers.splice(index, 1);
  27369. index--;
  27370. }
  27371. }
  27372. engine.bindSamplers(this);
  27373. this._compilationError = "";
  27374. this._isReady = true;
  27375. if (this.onCompiled) {
  27376. this.onCompiled(this);
  27377. }
  27378. this.onCompileObservable.notifyObservers(this);
  27379. this.onCompileObservable.clear();
  27380. // Unbind mesh reference in fallbacks
  27381. if (this._fallbacks) {
  27382. this._fallbacks.unBindMesh();
  27383. }
  27384. if (previousProgram) {
  27385. this.getEngine()._deleteProgram(previousProgram);
  27386. }
  27387. }
  27388. catch (e) {
  27389. this._compilationError = e.message;
  27390. // Let's go through fallbacks then
  27391. BABYLON.Tools.Error("Unable to compile effect:");
  27392. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  27393. return " " + uniform;
  27394. }));
  27395. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  27396. return " " + attribute;
  27397. }));
  27398. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  27399. BABYLON.Tools.Error("Error: " + this._compilationError);
  27400. if (previousProgram) {
  27401. this._program = previousProgram;
  27402. this._isReady = true;
  27403. if (this.onError) {
  27404. this.onError(this, this._compilationError);
  27405. }
  27406. this.onErrorObservable.notifyObservers(this);
  27407. }
  27408. if (fallbacks && fallbacks.isMoreFallbacks) {
  27409. BABYLON.Tools.Error("Trying next fallback.");
  27410. this.defines = fallbacks.reduce(this.defines);
  27411. this._prepareEffect();
  27412. }
  27413. else {
  27414. if (this.onError) {
  27415. this.onError(this, this._compilationError);
  27416. }
  27417. this.onErrorObservable.notifyObservers(this);
  27418. this.onErrorObservable.clear();
  27419. // Unbind mesh reference in fallbacks
  27420. if (this._fallbacks) {
  27421. this._fallbacks.unBindMesh();
  27422. }
  27423. }
  27424. }
  27425. };
  27426. Object.defineProperty(Effect.prototype, "isSupported", {
  27427. get: function () {
  27428. return this._compilationError === "";
  27429. },
  27430. enumerable: true,
  27431. configurable: true
  27432. });
  27433. Effect.prototype._bindTexture = function (channel, texture) {
  27434. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  27435. };
  27436. Effect.prototype.setTexture = function (channel, texture) {
  27437. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  27438. };
  27439. Effect.prototype.setTextureArray = function (channel, textures) {
  27440. if (this._samplers.indexOf(channel + "Ex") === -1) {
  27441. var initialPos = this._samplers.indexOf(channel);
  27442. for (var index = 1; index < textures.length; index++) {
  27443. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  27444. }
  27445. }
  27446. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  27447. };
  27448. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  27449. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  27450. };
  27451. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  27452. var cache = this._valueCache[uniformName];
  27453. var flag = matrix.updateFlag;
  27454. if (cache !== undefined && cache === flag) {
  27455. return false;
  27456. }
  27457. this._valueCache[uniformName] = flag;
  27458. return true;
  27459. };
  27460. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  27461. var cache = this._valueCache[uniformName];
  27462. if (!cache) {
  27463. cache = [x, y];
  27464. this._valueCache[uniformName] = cache;
  27465. return true;
  27466. }
  27467. var changed = false;
  27468. if (cache[0] !== x) {
  27469. cache[0] = x;
  27470. changed = true;
  27471. }
  27472. if (cache[1] !== y) {
  27473. cache[1] = y;
  27474. changed = true;
  27475. }
  27476. return changed;
  27477. };
  27478. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  27479. var cache = this._valueCache[uniformName];
  27480. if (!cache) {
  27481. cache = [x, y, z];
  27482. this._valueCache[uniformName] = cache;
  27483. return true;
  27484. }
  27485. var changed = false;
  27486. if (cache[0] !== x) {
  27487. cache[0] = x;
  27488. changed = true;
  27489. }
  27490. if (cache[1] !== y) {
  27491. cache[1] = y;
  27492. changed = true;
  27493. }
  27494. if (cache[2] !== z) {
  27495. cache[2] = z;
  27496. changed = true;
  27497. }
  27498. return changed;
  27499. };
  27500. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  27501. var cache = this._valueCache[uniformName];
  27502. if (!cache) {
  27503. cache = [x, y, z, w];
  27504. this._valueCache[uniformName] = cache;
  27505. return true;
  27506. }
  27507. var changed = false;
  27508. if (cache[0] !== x) {
  27509. cache[0] = x;
  27510. changed = true;
  27511. }
  27512. if (cache[1] !== y) {
  27513. cache[1] = y;
  27514. changed = true;
  27515. }
  27516. if (cache[2] !== z) {
  27517. cache[2] = z;
  27518. changed = true;
  27519. }
  27520. if (cache[3] !== w) {
  27521. cache[3] = w;
  27522. changed = true;
  27523. }
  27524. return changed;
  27525. };
  27526. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  27527. var bufferName = this._uniformBuffersNames[name];
  27528. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  27529. return;
  27530. }
  27531. Effect._baseCache[bufferName] = buffer;
  27532. this._engine.bindUniformBufferBase(buffer, bufferName);
  27533. };
  27534. Effect.prototype.bindUniformBlock = function (blockName, index) {
  27535. this._engine.bindUniformBlock(this._program, blockName, index);
  27536. };
  27537. Effect.prototype.setInt = function (uniformName, value) {
  27538. var cache = this._valueCache[uniformName];
  27539. if (cache !== undefined && cache === value)
  27540. return this;
  27541. this._valueCache[uniformName] = value;
  27542. this._engine.setInt(this.getUniform(uniformName), value);
  27543. return this;
  27544. };
  27545. Effect.prototype.setIntArray = function (uniformName, array) {
  27546. this._valueCache[uniformName] = null;
  27547. this._engine.setIntArray(this.getUniform(uniformName), array);
  27548. return this;
  27549. };
  27550. Effect.prototype.setIntArray2 = function (uniformName, array) {
  27551. this._valueCache[uniformName] = null;
  27552. this._engine.setIntArray2(this.getUniform(uniformName), array);
  27553. return this;
  27554. };
  27555. Effect.prototype.setIntArray3 = function (uniformName, array) {
  27556. this._valueCache[uniformName] = null;
  27557. this._engine.setIntArray3(this.getUniform(uniformName), array);
  27558. return this;
  27559. };
  27560. Effect.prototype.setIntArray4 = function (uniformName, array) {
  27561. this._valueCache[uniformName] = null;
  27562. this._engine.setIntArray4(this.getUniform(uniformName), array);
  27563. return this;
  27564. };
  27565. Effect.prototype.setFloatArray = function (uniformName, array) {
  27566. this._valueCache[uniformName] = null;
  27567. this._engine.setFloatArray(this.getUniform(uniformName), array);
  27568. return this;
  27569. };
  27570. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  27571. this._valueCache[uniformName] = null;
  27572. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  27573. return this;
  27574. };
  27575. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  27576. this._valueCache[uniformName] = null;
  27577. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  27578. return this;
  27579. };
  27580. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  27581. this._valueCache[uniformName] = null;
  27582. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  27583. return this;
  27584. };
  27585. Effect.prototype.setArray = function (uniformName, array) {
  27586. this._valueCache[uniformName] = null;
  27587. this._engine.setArray(this.getUniform(uniformName), array);
  27588. return this;
  27589. };
  27590. Effect.prototype.setArray2 = function (uniformName, array) {
  27591. this._valueCache[uniformName] = null;
  27592. this._engine.setArray2(this.getUniform(uniformName), array);
  27593. return this;
  27594. };
  27595. Effect.prototype.setArray3 = function (uniformName, array) {
  27596. this._valueCache[uniformName] = null;
  27597. this._engine.setArray3(this.getUniform(uniformName), array);
  27598. return this;
  27599. };
  27600. Effect.prototype.setArray4 = function (uniformName, array) {
  27601. this._valueCache[uniformName] = null;
  27602. this._engine.setArray4(this.getUniform(uniformName), array);
  27603. return this;
  27604. };
  27605. Effect.prototype.setMatrices = function (uniformName, matrices) {
  27606. if (!matrices) {
  27607. return this;
  27608. }
  27609. this._valueCache[uniformName] = null;
  27610. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  27611. return this;
  27612. };
  27613. Effect.prototype.setMatrix = function (uniformName, matrix) {
  27614. if (this._cacheMatrix(uniformName, matrix)) {
  27615. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  27616. }
  27617. return this;
  27618. };
  27619. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  27620. this._valueCache[uniformName] = null;
  27621. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  27622. return this;
  27623. };
  27624. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  27625. this._valueCache[uniformName] = null;
  27626. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  27627. return this;
  27628. };
  27629. Effect.prototype.setFloat = function (uniformName, value) {
  27630. var cache = this._valueCache[uniformName];
  27631. if (cache !== undefined && cache === value)
  27632. return this;
  27633. this._valueCache[uniformName] = value;
  27634. this._engine.setFloat(this.getUniform(uniformName), value);
  27635. return this;
  27636. };
  27637. Effect.prototype.setBool = function (uniformName, bool) {
  27638. var cache = this._valueCache[uniformName];
  27639. if (cache !== undefined && cache === bool)
  27640. return this;
  27641. this._valueCache[uniformName] = bool;
  27642. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  27643. return this;
  27644. };
  27645. Effect.prototype.setVector2 = function (uniformName, vector2) {
  27646. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  27647. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  27648. }
  27649. return this;
  27650. };
  27651. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  27652. if (this._cacheFloat2(uniformName, x, y)) {
  27653. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  27654. }
  27655. return this;
  27656. };
  27657. Effect.prototype.setVector3 = function (uniformName, vector3) {
  27658. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  27659. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  27660. }
  27661. return this;
  27662. };
  27663. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  27664. if (this._cacheFloat3(uniformName, x, y, z)) {
  27665. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  27666. }
  27667. return this;
  27668. };
  27669. Effect.prototype.setVector4 = function (uniformName, vector4) {
  27670. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  27671. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  27672. }
  27673. return this;
  27674. };
  27675. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  27676. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  27677. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  27678. }
  27679. return this;
  27680. };
  27681. Effect.prototype.setColor3 = function (uniformName, color3) {
  27682. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  27683. this._engine.setColor3(this.getUniform(uniformName), color3);
  27684. }
  27685. return this;
  27686. };
  27687. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  27688. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  27689. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  27690. }
  27691. return this;
  27692. };
  27693. Effect.ResetCache = function () {
  27694. Effect._baseCache = {};
  27695. };
  27696. Effect._uniqueIdSeed = 0;
  27697. Effect._baseCache = {};
  27698. // Statics
  27699. Effect.ShadersStore = {};
  27700. Effect.IncludesShadersStore = {};
  27701. return Effect;
  27702. }());
  27703. BABYLON.Effect = Effect;
  27704. })(BABYLON || (BABYLON = {}));
  27705. //# sourceMappingURL=babylon.effect.js.map
  27706. var __assign = (this && this.__assign) || Object.assign || function(t) {
  27707. for (var s, i = 1, n = arguments.length; i < n; i++) {
  27708. s = arguments[i];
  27709. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  27710. t[p] = s[p];
  27711. }
  27712. return t;
  27713. };
  27714. var BABYLON;
  27715. (function (BABYLON) {
  27716. var MaterialDefines = /** @class */ (function () {
  27717. function MaterialDefines() {
  27718. this._isDirty = true;
  27719. this._areLightsDirty = true;
  27720. this._areAttributesDirty = true;
  27721. this._areTexturesDirty = true;
  27722. this._areFresnelDirty = true;
  27723. this._areMiscDirty = true;
  27724. this._areImageProcessingDirty = true;
  27725. this._normals = false;
  27726. this._uvs = false;
  27727. this._needNormals = false;
  27728. this._needUVs = false;
  27729. }
  27730. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  27731. get: function () {
  27732. return this._isDirty;
  27733. },
  27734. enumerable: true,
  27735. configurable: true
  27736. });
  27737. MaterialDefines.prototype.markAsProcessed = function () {
  27738. this._isDirty = false;
  27739. this._areAttributesDirty = false;
  27740. this._areTexturesDirty = false;
  27741. this._areFresnelDirty = false;
  27742. this._areLightsDirty = false;
  27743. this._areMiscDirty = false;
  27744. this._areImageProcessingDirty = false;
  27745. };
  27746. MaterialDefines.prototype.markAsUnprocessed = function () {
  27747. this._isDirty = true;
  27748. };
  27749. MaterialDefines.prototype.markAllAsDirty = function () {
  27750. this._areTexturesDirty = true;
  27751. this._areAttributesDirty = true;
  27752. this._areLightsDirty = true;
  27753. this._areFresnelDirty = true;
  27754. this._areMiscDirty = true;
  27755. this._areImageProcessingDirty = true;
  27756. this._isDirty = true;
  27757. };
  27758. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  27759. this._areImageProcessingDirty = true;
  27760. this._isDirty = true;
  27761. };
  27762. MaterialDefines.prototype.markAsLightDirty = function () {
  27763. this._areLightsDirty = true;
  27764. this._isDirty = true;
  27765. };
  27766. MaterialDefines.prototype.markAsAttributesDirty = function () {
  27767. this._areAttributesDirty = true;
  27768. this._isDirty = true;
  27769. };
  27770. MaterialDefines.prototype.markAsTexturesDirty = function () {
  27771. this._areTexturesDirty = true;
  27772. this._isDirty = true;
  27773. };
  27774. MaterialDefines.prototype.markAsFresnelDirty = function () {
  27775. this._areFresnelDirty = true;
  27776. this._isDirty = true;
  27777. };
  27778. MaterialDefines.prototype.markAsMiscDirty = function () {
  27779. this._areMiscDirty = true;
  27780. this._isDirty = true;
  27781. };
  27782. MaterialDefines.prototype.rebuild = function () {
  27783. if (this._keys) {
  27784. delete this._keys;
  27785. }
  27786. this._keys = [];
  27787. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  27788. var key = _a[_i];
  27789. if (key[0] === "_") {
  27790. continue;
  27791. }
  27792. this._keys.push(key);
  27793. }
  27794. };
  27795. MaterialDefines.prototype.isEqual = function (other) {
  27796. if (this._keys.length !== other._keys.length) {
  27797. return false;
  27798. }
  27799. for (var index = 0; index < this._keys.length; index++) {
  27800. var prop = this._keys[index];
  27801. if (this[prop] !== other[prop]) {
  27802. return false;
  27803. }
  27804. }
  27805. return true;
  27806. };
  27807. MaterialDefines.prototype.cloneTo = function (other) {
  27808. if (this._keys.length !== other._keys.length) {
  27809. other._keys = this._keys.slice(0);
  27810. }
  27811. for (var index = 0; index < this._keys.length; index++) {
  27812. var prop = this._keys[index];
  27813. other[prop] = this[prop];
  27814. }
  27815. };
  27816. MaterialDefines.prototype.reset = function () {
  27817. for (var index = 0; index < this._keys.length; index++) {
  27818. var prop = this._keys[index];
  27819. if (typeof (this[prop]) === "number") {
  27820. this[prop] = 0;
  27821. }
  27822. else {
  27823. this[prop] = false;
  27824. }
  27825. }
  27826. };
  27827. MaterialDefines.prototype.toString = function () {
  27828. var result = "";
  27829. for (var index = 0; index < this._keys.length; index++) {
  27830. var prop = this._keys[index];
  27831. var value = this[prop];
  27832. if (typeof (value) === "number") {
  27833. result += "#define " + prop + " " + this[prop] + "\n";
  27834. }
  27835. else if (value) {
  27836. result += "#define " + prop + "\n";
  27837. }
  27838. }
  27839. return result;
  27840. };
  27841. return MaterialDefines;
  27842. }());
  27843. BABYLON.MaterialDefines = MaterialDefines;
  27844. var Material = /** @class */ (function () {
  27845. function Material(name, scene, doNotAdd) {
  27846. this.checkReadyOnEveryCall = false;
  27847. this.checkReadyOnlyOnce = false;
  27848. this.state = "";
  27849. this.alpha = 1.0;
  27850. this._backFaceCulling = true;
  27851. this.doNotSerialize = false;
  27852. this.storeEffectOnSubMeshes = false;
  27853. /**
  27854. * An event triggered when the material is disposed.
  27855. * @type {BABYLON.Observable}
  27856. */
  27857. this.onDisposeObservable = new BABYLON.Observable();
  27858. /**
  27859. * An event triggered when the material is bound.
  27860. * @type {BABYLON.Observable}
  27861. */
  27862. this.onBindObservable = new BABYLON.Observable();
  27863. /**
  27864. * An event triggered when the material is unbound.
  27865. * @type {BABYLON.Observable}
  27866. */
  27867. this.onUnBindObservable = new BABYLON.Observable();
  27868. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  27869. this._needDepthPrePass = false;
  27870. this.disableDepthWrite = false;
  27871. this.forceDepthWrite = false;
  27872. this.separateCullingPass = false;
  27873. this._fogEnabled = true;
  27874. this.pointSize = 1.0;
  27875. this.zOffset = 0;
  27876. this._wasPreviouslyReady = false;
  27877. this._fillMode = Material.TriangleFillMode;
  27878. this.name = name;
  27879. this.id = name || BABYLON.Tools.RandomId();
  27880. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  27881. if (this._scene.useRightHandedSystem) {
  27882. this.sideOrientation = Material.ClockWiseSideOrientation;
  27883. }
  27884. else {
  27885. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  27886. }
  27887. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  27888. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  27889. if (!doNotAdd) {
  27890. this._scene.materials.push(this);
  27891. }
  27892. }
  27893. Object.defineProperty(Material, "TriangleFillMode", {
  27894. get: function () {
  27895. return Material._TriangleFillMode;
  27896. },
  27897. enumerable: true,
  27898. configurable: true
  27899. });
  27900. Object.defineProperty(Material, "WireFrameFillMode", {
  27901. get: function () {
  27902. return Material._WireFrameFillMode;
  27903. },
  27904. enumerable: true,
  27905. configurable: true
  27906. });
  27907. Object.defineProperty(Material, "PointFillMode", {
  27908. get: function () {
  27909. return Material._PointFillMode;
  27910. },
  27911. enumerable: true,
  27912. configurable: true
  27913. });
  27914. Object.defineProperty(Material, "PointListDrawMode", {
  27915. get: function () {
  27916. return Material._PointListDrawMode;
  27917. },
  27918. enumerable: true,
  27919. configurable: true
  27920. });
  27921. Object.defineProperty(Material, "LineListDrawMode", {
  27922. get: function () {
  27923. return Material._LineListDrawMode;
  27924. },
  27925. enumerable: true,
  27926. configurable: true
  27927. });
  27928. Object.defineProperty(Material, "LineLoopDrawMode", {
  27929. get: function () {
  27930. return Material._LineLoopDrawMode;
  27931. },
  27932. enumerable: true,
  27933. configurable: true
  27934. });
  27935. Object.defineProperty(Material, "LineStripDrawMode", {
  27936. get: function () {
  27937. return Material._LineStripDrawMode;
  27938. },
  27939. enumerable: true,
  27940. configurable: true
  27941. });
  27942. Object.defineProperty(Material, "TriangleStripDrawMode", {
  27943. get: function () {
  27944. return Material._TriangleStripDrawMode;
  27945. },
  27946. enumerable: true,
  27947. configurable: true
  27948. });
  27949. Object.defineProperty(Material, "TriangleFanDrawMode", {
  27950. get: function () {
  27951. return Material._TriangleFanDrawMode;
  27952. },
  27953. enumerable: true,
  27954. configurable: true
  27955. });
  27956. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  27957. get: function () {
  27958. return Material._ClockWiseSideOrientation;
  27959. },
  27960. enumerable: true,
  27961. configurable: true
  27962. });
  27963. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  27964. get: function () {
  27965. return Material._CounterClockWiseSideOrientation;
  27966. },
  27967. enumerable: true,
  27968. configurable: true
  27969. });
  27970. Object.defineProperty(Material, "TextureDirtyFlag", {
  27971. get: function () {
  27972. return Material._TextureDirtyFlag;
  27973. },
  27974. enumerable: true,
  27975. configurable: true
  27976. });
  27977. Object.defineProperty(Material, "LightDirtyFlag", {
  27978. get: function () {
  27979. return Material._LightDirtyFlag;
  27980. },
  27981. enumerable: true,
  27982. configurable: true
  27983. });
  27984. Object.defineProperty(Material, "FresnelDirtyFlag", {
  27985. get: function () {
  27986. return Material._FresnelDirtyFlag;
  27987. },
  27988. enumerable: true,
  27989. configurable: true
  27990. });
  27991. Object.defineProperty(Material, "AttributesDirtyFlag", {
  27992. get: function () {
  27993. return Material._AttributesDirtyFlag;
  27994. },
  27995. enumerable: true,
  27996. configurable: true
  27997. });
  27998. Object.defineProperty(Material, "MiscDirtyFlag", {
  27999. get: function () {
  28000. return Material._MiscDirtyFlag;
  28001. },
  28002. enumerable: true,
  28003. configurable: true
  28004. });
  28005. Object.defineProperty(Material.prototype, "backFaceCulling", {
  28006. get: function () {
  28007. return this._backFaceCulling;
  28008. },
  28009. set: function (value) {
  28010. if (this._backFaceCulling === value) {
  28011. return;
  28012. }
  28013. this._backFaceCulling = value;
  28014. this.markAsDirty(Material.TextureDirtyFlag);
  28015. },
  28016. enumerable: true,
  28017. configurable: true
  28018. });
  28019. Object.defineProperty(Material.prototype, "onDispose", {
  28020. set: function (callback) {
  28021. if (this._onDisposeObserver) {
  28022. this.onDisposeObservable.remove(this._onDisposeObserver);
  28023. }
  28024. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28025. },
  28026. enumerable: true,
  28027. configurable: true
  28028. });
  28029. Object.defineProperty(Material.prototype, "onBind", {
  28030. set: function (callback) {
  28031. if (this._onBindObserver) {
  28032. this.onBindObservable.remove(this._onBindObserver);
  28033. }
  28034. this._onBindObserver = this.onBindObservable.add(callback);
  28035. },
  28036. enumerable: true,
  28037. configurable: true
  28038. });
  28039. Object.defineProperty(Material.prototype, "alphaMode", {
  28040. get: function () {
  28041. return this._alphaMode;
  28042. },
  28043. set: function (value) {
  28044. if (this._alphaMode === value) {
  28045. return;
  28046. }
  28047. this._alphaMode = value;
  28048. this.markAsDirty(Material.TextureDirtyFlag);
  28049. },
  28050. enumerable: true,
  28051. configurable: true
  28052. });
  28053. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  28054. get: function () {
  28055. return this._needDepthPrePass;
  28056. },
  28057. set: function (value) {
  28058. if (this._needDepthPrePass === value) {
  28059. return;
  28060. }
  28061. this._needDepthPrePass = value;
  28062. if (this._needDepthPrePass) {
  28063. this.checkReadyOnEveryCall = true;
  28064. }
  28065. },
  28066. enumerable: true,
  28067. configurable: true
  28068. });
  28069. Object.defineProperty(Material.prototype, "fogEnabled", {
  28070. get: function () {
  28071. return this._fogEnabled;
  28072. },
  28073. set: function (value) {
  28074. if (this._fogEnabled === value) {
  28075. return;
  28076. }
  28077. this._fogEnabled = value;
  28078. this.markAsDirty(Material.MiscDirtyFlag);
  28079. },
  28080. enumerable: true,
  28081. configurable: true
  28082. });
  28083. Object.defineProperty(Material.prototype, "wireframe", {
  28084. get: function () {
  28085. return this._fillMode === Material.WireFrameFillMode;
  28086. },
  28087. set: function (value) {
  28088. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  28089. },
  28090. enumerable: true,
  28091. configurable: true
  28092. });
  28093. Object.defineProperty(Material.prototype, "pointsCloud", {
  28094. get: function () {
  28095. return this._fillMode === Material.PointFillMode;
  28096. },
  28097. set: function (value) {
  28098. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  28099. },
  28100. enumerable: true,
  28101. configurable: true
  28102. });
  28103. Object.defineProperty(Material.prototype, "fillMode", {
  28104. get: function () {
  28105. return this._fillMode;
  28106. },
  28107. set: function (value) {
  28108. if (this._fillMode === value) {
  28109. return;
  28110. }
  28111. this._fillMode = value;
  28112. this.markAsDirty(Material.MiscDirtyFlag);
  28113. },
  28114. enumerable: true,
  28115. configurable: true
  28116. });
  28117. /**
  28118. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28119. * subclasses should override adding information pertainent to themselves
  28120. */
  28121. Material.prototype.toString = function (fullDetails) {
  28122. var ret = "Name: " + this.name;
  28123. if (fullDetails) {
  28124. }
  28125. return ret;
  28126. };
  28127. /**
  28128. * Child classes can use it to update shaders
  28129. */
  28130. Material.prototype.getClassName = function () {
  28131. return "Material";
  28132. };
  28133. Object.defineProperty(Material.prototype, "isFrozen", {
  28134. get: function () {
  28135. return this.checkReadyOnlyOnce;
  28136. },
  28137. enumerable: true,
  28138. configurable: true
  28139. });
  28140. Material.prototype.freeze = function () {
  28141. this.checkReadyOnlyOnce = true;
  28142. };
  28143. Material.prototype.unfreeze = function () {
  28144. this.checkReadyOnlyOnce = false;
  28145. };
  28146. Material.prototype.isReady = function (mesh, useInstances) {
  28147. return true;
  28148. };
  28149. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  28150. return false;
  28151. };
  28152. Material.prototype.getEffect = function () {
  28153. return this._effect;
  28154. };
  28155. Material.prototype.getScene = function () {
  28156. return this._scene;
  28157. };
  28158. Material.prototype.needAlphaBlending = function () {
  28159. return (this.alpha < 1.0);
  28160. };
  28161. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  28162. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  28163. };
  28164. Material.prototype.needAlphaTesting = function () {
  28165. return false;
  28166. };
  28167. Material.prototype.getAlphaTestTexture = function () {
  28168. return null;
  28169. };
  28170. Material.prototype.markDirty = function () {
  28171. this._wasPreviouslyReady = false;
  28172. };
  28173. Material.prototype._preBind = function (effect, overrideOrientation) {
  28174. if (overrideOrientation === void 0) { overrideOrientation = null; }
  28175. var engine = this._scene.getEngine();
  28176. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  28177. var reverse = orientation === Material.ClockWiseSideOrientation;
  28178. engine.enableEffect(effect ? effect : this._effect);
  28179. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  28180. return reverse;
  28181. };
  28182. Material.prototype.bind = function (world, mesh) {
  28183. };
  28184. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  28185. };
  28186. Material.prototype.bindOnlyWorldMatrix = function (world) {
  28187. };
  28188. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  28189. sceneUbo.bindToEffect(effect, "Scene");
  28190. };
  28191. Material.prototype.bindView = function (effect) {
  28192. if (!this._useUBO) {
  28193. effect.setMatrix("view", this.getScene().getViewMatrix());
  28194. }
  28195. else {
  28196. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  28197. }
  28198. };
  28199. Material.prototype.bindViewProjection = function (effect) {
  28200. if (!this._useUBO) {
  28201. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  28202. }
  28203. else {
  28204. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  28205. }
  28206. };
  28207. Material.prototype._afterBind = function (mesh) {
  28208. this._scene._cachedMaterial = this;
  28209. if (mesh) {
  28210. this._scene._cachedVisibility = mesh.visibility;
  28211. }
  28212. else {
  28213. this._scene._cachedVisibility = 1;
  28214. }
  28215. if (mesh) {
  28216. this.onBindObservable.notifyObservers(mesh);
  28217. }
  28218. if (this.disableDepthWrite) {
  28219. var engine = this._scene.getEngine();
  28220. this._cachedDepthWriteState = engine.getDepthWrite();
  28221. engine.setDepthWrite(false);
  28222. }
  28223. };
  28224. Material.prototype.unbind = function () {
  28225. this.onUnBindObservable.notifyObservers(this);
  28226. if (this.disableDepthWrite) {
  28227. var engine = this._scene.getEngine();
  28228. engine.setDepthWrite(this._cachedDepthWriteState);
  28229. }
  28230. };
  28231. Material.prototype.getActiveTextures = function () {
  28232. return [];
  28233. };
  28234. Material.prototype.hasTexture = function (texture) {
  28235. return false;
  28236. };
  28237. Material.prototype.clone = function (name) {
  28238. return null;
  28239. };
  28240. Material.prototype.getBindedMeshes = function () {
  28241. var result = new Array();
  28242. for (var index = 0; index < this._scene.meshes.length; index++) {
  28243. var mesh = this._scene.meshes[index];
  28244. if (mesh.material === this) {
  28245. result.push(mesh);
  28246. }
  28247. }
  28248. return result;
  28249. };
  28250. /**
  28251. * Force shader compilation including textures ready check
  28252. */
  28253. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  28254. var _this = this;
  28255. var localOptions = __assign({ alphaTest: null, clipPlane: false }, options);
  28256. var subMesh = new BABYLON.BaseSubMesh();
  28257. var scene = this.getScene();
  28258. var engine = scene.getEngine();
  28259. var checkReady = function () {
  28260. if (!_this._scene || !_this._scene.getEngine()) {
  28261. return;
  28262. }
  28263. if (subMesh._materialDefines) {
  28264. subMesh._materialDefines._renderId = -1;
  28265. }
  28266. var alphaTestState = engine.getAlphaTesting();
  28267. var clipPlaneState = scene.clipPlane;
  28268. engine.setAlphaTesting(localOptions.alphaTest || (!_this.needAlphaBlendingForMesh(mesh) && _this.needAlphaTesting()));
  28269. if (localOptions.clipPlane) {
  28270. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  28271. }
  28272. if (_this.storeEffectOnSubMeshes) {
  28273. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  28274. if (onCompiled) {
  28275. onCompiled(_this);
  28276. }
  28277. }
  28278. else {
  28279. setTimeout(checkReady, 16);
  28280. }
  28281. }
  28282. else {
  28283. if (_this.isReady(mesh)) {
  28284. if (onCompiled) {
  28285. onCompiled(_this);
  28286. }
  28287. }
  28288. else {
  28289. setTimeout(checkReady, 16);
  28290. }
  28291. }
  28292. engine.setAlphaTesting(alphaTestState);
  28293. if (options && options.clipPlane) {
  28294. scene.clipPlane = clipPlaneState;
  28295. }
  28296. };
  28297. checkReady();
  28298. };
  28299. Material.prototype.markAsDirty = function (flag) {
  28300. if (flag & Material.TextureDirtyFlag) {
  28301. this._markAllSubMeshesAsTexturesDirty();
  28302. }
  28303. if (flag & Material.LightDirtyFlag) {
  28304. this._markAllSubMeshesAsLightsDirty();
  28305. }
  28306. if (flag & Material.FresnelDirtyFlag) {
  28307. this._markAllSubMeshesAsFresnelDirty();
  28308. }
  28309. if (flag & Material.AttributesDirtyFlag) {
  28310. this._markAllSubMeshesAsAttributesDirty();
  28311. }
  28312. if (flag & Material.MiscDirtyFlag) {
  28313. this._markAllSubMeshesAsMiscDirty();
  28314. }
  28315. this.getScene().resetCachedMaterial();
  28316. };
  28317. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  28318. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  28319. var mesh = _a[_i];
  28320. if (!mesh.subMeshes) {
  28321. continue;
  28322. }
  28323. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  28324. var subMesh = _c[_b];
  28325. if (subMesh.getMaterial() !== this) {
  28326. continue;
  28327. }
  28328. if (!subMesh._materialDefines) {
  28329. continue;
  28330. }
  28331. func(subMesh._materialDefines);
  28332. }
  28333. }
  28334. };
  28335. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  28336. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  28337. };
  28338. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  28339. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  28340. };
  28341. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  28342. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  28343. };
  28344. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  28345. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  28346. };
  28347. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  28348. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  28349. };
  28350. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  28351. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  28352. };
  28353. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  28354. // Animations
  28355. this.getScene().stopAnimation(this);
  28356. // Remove from scene
  28357. var index = this._scene.materials.indexOf(this);
  28358. if (index >= 0) {
  28359. this._scene.materials.splice(index, 1);
  28360. }
  28361. // Remove from meshes
  28362. for (index = 0; index < this._scene.meshes.length; index++) {
  28363. var mesh = this._scene.meshes[index];
  28364. if (mesh.material === this) {
  28365. mesh.material = null;
  28366. if (mesh.geometry) {
  28367. var geometry = (mesh.geometry);
  28368. if (this.storeEffectOnSubMeshes) {
  28369. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  28370. var subMesh = _a[_i];
  28371. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  28372. if (forceDisposeEffect && subMesh._materialEffect) {
  28373. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  28374. }
  28375. }
  28376. }
  28377. else {
  28378. geometry._releaseVertexArrayObject(this._effect);
  28379. }
  28380. }
  28381. }
  28382. }
  28383. this._uniformBuffer.dispose();
  28384. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  28385. if (forceDisposeEffect && this._effect) {
  28386. if (!this.storeEffectOnSubMeshes) {
  28387. this._scene.getEngine()._releaseEffect(this._effect);
  28388. }
  28389. this._effect = null;
  28390. }
  28391. // Callback
  28392. this.onDisposeObservable.notifyObservers(this);
  28393. this.onDisposeObservable.clear();
  28394. this.onBindObservable.clear();
  28395. this.onUnBindObservable.clear();
  28396. };
  28397. Material.prototype.serialize = function () {
  28398. return BABYLON.SerializationHelper.Serialize(this);
  28399. };
  28400. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  28401. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  28402. multiMaterial.id = parsedMultiMaterial.id;
  28403. if (BABYLON.Tags) {
  28404. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  28405. }
  28406. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  28407. var subMatId = parsedMultiMaterial.materials[matIndex];
  28408. if (subMatId) {
  28409. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  28410. }
  28411. else {
  28412. multiMaterial.subMaterials.push(null);
  28413. }
  28414. }
  28415. return multiMaterial;
  28416. };
  28417. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  28418. if (!parsedMaterial.customType) {
  28419. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  28420. }
  28421. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  28422. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  28423. if (!BABYLON.LegacyPBRMaterial) {
  28424. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  28425. return;
  28426. }
  28427. }
  28428. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  28429. return materialType.Parse(parsedMaterial, scene, rootUrl);
  28430. ;
  28431. };
  28432. // Triangle views
  28433. Material._TriangleFillMode = 0;
  28434. Material._WireFrameFillMode = 1;
  28435. Material._PointFillMode = 2;
  28436. // Draw modes
  28437. Material._PointListDrawMode = 3;
  28438. Material._LineListDrawMode = 4;
  28439. Material._LineLoopDrawMode = 5;
  28440. Material._LineStripDrawMode = 6;
  28441. Material._TriangleStripDrawMode = 7;
  28442. Material._TriangleFanDrawMode = 8;
  28443. Material._ClockWiseSideOrientation = 0;
  28444. Material._CounterClockWiseSideOrientation = 1;
  28445. Material._TextureDirtyFlag = 1;
  28446. Material._LightDirtyFlag = 2;
  28447. Material._FresnelDirtyFlag = 4;
  28448. Material._AttributesDirtyFlag = 8;
  28449. Material._MiscDirtyFlag = 16;
  28450. __decorate([
  28451. BABYLON.serialize()
  28452. ], Material.prototype, "id", void 0);
  28453. __decorate([
  28454. BABYLON.serialize()
  28455. ], Material.prototype, "name", void 0);
  28456. __decorate([
  28457. BABYLON.serialize()
  28458. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  28459. __decorate([
  28460. BABYLON.serialize()
  28461. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  28462. __decorate([
  28463. BABYLON.serialize()
  28464. ], Material.prototype, "state", void 0);
  28465. __decorate([
  28466. BABYLON.serialize()
  28467. ], Material.prototype, "alpha", void 0);
  28468. __decorate([
  28469. BABYLON.serialize("backFaceCulling")
  28470. ], Material.prototype, "_backFaceCulling", void 0);
  28471. __decorate([
  28472. BABYLON.serialize()
  28473. ], Material.prototype, "sideOrientation", void 0);
  28474. __decorate([
  28475. BABYLON.serialize("alphaMode")
  28476. ], Material.prototype, "_alphaMode", void 0);
  28477. __decorate([
  28478. BABYLON.serialize()
  28479. ], Material.prototype, "_needDepthPrePass", void 0);
  28480. __decorate([
  28481. BABYLON.serialize()
  28482. ], Material.prototype, "disableDepthWrite", void 0);
  28483. __decorate([
  28484. BABYLON.serialize()
  28485. ], Material.prototype, "forceDepthWrite", void 0);
  28486. __decorate([
  28487. BABYLON.serialize()
  28488. ], Material.prototype, "separateCullingPass", void 0);
  28489. __decorate([
  28490. BABYLON.serialize("fogEnabled")
  28491. ], Material.prototype, "_fogEnabled", void 0);
  28492. __decorate([
  28493. BABYLON.serialize()
  28494. ], Material.prototype, "pointSize", void 0);
  28495. __decorate([
  28496. BABYLON.serialize()
  28497. ], Material.prototype, "zOffset", void 0);
  28498. __decorate([
  28499. BABYLON.serialize()
  28500. ], Material.prototype, "wireframe", null);
  28501. __decorate([
  28502. BABYLON.serialize()
  28503. ], Material.prototype, "pointsCloud", null);
  28504. __decorate([
  28505. BABYLON.serialize()
  28506. ], Material.prototype, "fillMode", null);
  28507. return Material;
  28508. }());
  28509. BABYLON.Material = Material;
  28510. })(BABYLON || (BABYLON = {}));
  28511. //# sourceMappingURL=babylon.material.js.map
  28512. var BABYLON;
  28513. (function (BABYLON) {
  28514. var UniformBuffer = /** @class */ (function () {
  28515. /**
  28516. * Uniform buffer objects.
  28517. *
  28518. * Handles blocks of uniform on the GPU.
  28519. *
  28520. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  28521. *
  28522. * For more information, please refer to :
  28523. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  28524. */
  28525. function UniformBuffer(engine, data, dynamic) {
  28526. this._engine = engine;
  28527. this._noUBO = !engine.supportsUniformBuffers;
  28528. this._dynamic = dynamic;
  28529. this._data = data || [];
  28530. this._uniformLocations = {};
  28531. this._uniformSizes = {};
  28532. this._uniformLocationPointer = 0;
  28533. this._needSync = false;
  28534. if (this._noUBO) {
  28535. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  28536. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  28537. this.updateFloat = this._updateFloatForEffect;
  28538. this.updateFloat2 = this._updateFloat2ForEffect;
  28539. this.updateFloat3 = this._updateFloat3ForEffect;
  28540. this.updateFloat4 = this._updateFloat4ForEffect;
  28541. this.updateMatrix = this._updateMatrixForEffect;
  28542. this.updateVector3 = this._updateVector3ForEffect;
  28543. this.updateVector4 = this._updateVector4ForEffect;
  28544. this.updateColor3 = this._updateColor3ForEffect;
  28545. this.updateColor4 = this._updateColor4ForEffect;
  28546. }
  28547. else {
  28548. this._engine._uniformBuffers.push(this);
  28549. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  28550. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  28551. this.updateFloat = this._updateFloatForUniform;
  28552. this.updateFloat2 = this._updateFloat2ForUniform;
  28553. this.updateFloat3 = this._updateFloat3ForUniform;
  28554. this.updateFloat4 = this._updateFloat4ForUniform;
  28555. this.updateMatrix = this._updateMatrixForUniform;
  28556. this.updateVector3 = this._updateVector3ForUniform;
  28557. this.updateVector4 = this._updateVector4ForUniform;
  28558. this.updateColor3 = this._updateColor3ForUniform;
  28559. this.updateColor4 = this._updateColor4ForUniform;
  28560. }
  28561. }
  28562. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  28563. // Properties
  28564. /**
  28565. * Indicates if the buffer is using the WebGL2 UBO implementation,
  28566. * or just falling back on setUniformXXX calls.
  28567. */
  28568. get: function () {
  28569. return !this._noUBO;
  28570. },
  28571. enumerable: true,
  28572. configurable: true
  28573. });
  28574. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  28575. /**
  28576. * Indicates if the WebGL underlying uniform buffer is in sync
  28577. * with the javascript cache data.
  28578. */
  28579. get: function () {
  28580. return !this._needSync;
  28581. },
  28582. enumerable: true,
  28583. configurable: true
  28584. });
  28585. /**
  28586. * Indicates if the WebGL underlying uniform buffer is dynamic.
  28587. * Also, a dynamic UniformBuffer will disable cache verification and always
  28588. * update the underlying WebGL uniform buffer to the GPU.
  28589. */
  28590. UniformBuffer.prototype.isDynamic = function () {
  28591. return this._dynamic !== undefined;
  28592. };
  28593. /**
  28594. * The data cache on JS side.
  28595. */
  28596. UniformBuffer.prototype.getData = function () {
  28597. return this._bufferData;
  28598. };
  28599. /**
  28600. * The underlying WebGL Uniform buffer.
  28601. */
  28602. UniformBuffer.prototype.getBuffer = function () {
  28603. return this._buffer;
  28604. };
  28605. /**
  28606. * std140 layout specifies how to align data within an UBO structure.
  28607. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  28608. * for specs.
  28609. */
  28610. UniformBuffer.prototype._fillAlignment = function (size) {
  28611. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  28612. // and 4x4 matrices
  28613. // TODO : change if other types are used
  28614. var alignment;
  28615. if (size <= 2) {
  28616. alignment = size;
  28617. }
  28618. else {
  28619. alignment = 4;
  28620. }
  28621. if ((this._uniformLocationPointer % alignment) !== 0) {
  28622. var oldPointer = this._uniformLocationPointer;
  28623. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  28624. var diff = this._uniformLocationPointer - oldPointer;
  28625. for (var i = 0; i < diff; i++) {
  28626. this._data.push(0);
  28627. }
  28628. }
  28629. };
  28630. /**
  28631. * Adds an uniform in the buffer.
  28632. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  28633. * for the layout to be correct !
  28634. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28635. * @param {number|number[]} size Data size, or data directly.
  28636. */
  28637. UniformBuffer.prototype.addUniform = function (name, size) {
  28638. if (this._noUBO) {
  28639. return;
  28640. }
  28641. if (this._uniformLocations[name] !== undefined) {
  28642. // Already existing uniform
  28643. return;
  28644. }
  28645. // This function must be called in the order of the shader layout !
  28646. // size can be the size of the uniform, or data directly
  28647. var data;
  28648. if (size instanceof Array) {
  28649. data = size;
  28650. size = data.length;
  28651. }
  28652. else {
  28653. size = size;
  28654. data = [];
  28655. // Fill with zeros
  28656. for (var i = 0; i < size; i++) {
  28657. data.push(0);
  28658. }
  28659. }
  28660. this._fillAlignment(size);
  28661. this._uniformSizes[name] = size;
  28662. this._uniformLocations[name] = this._uniformLocationPointer;
  28663. this._uniformLocationPointer += size;
  28664. for (var i = 0; i < size; i++) {
  28665. this._data.push(data[i]);
  28666. }
  28667. this._needSync = true;
  28668. };
  28669. /**
  28670. * Wrapper for addUniform.
  28671. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28672. * @param {Matrix} mat A 4x4 matrix.
  28673. */
  28674. UniformBuffer.prototype.addMatrix = function (name, mat) {
  28675. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  28676. };
  28677. /**
  28678. * Wrapper for addUniform.
  28679. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28680. * @param {number} x
  28681. * @param {number} y
  28682. */
  28683. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  28684. var temp = [x, y];
  28685. this.addUniform(name, temp);
  28686. };
  28687. /**
  28688. * Wrapper for addUniform.
  28689. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28690. * @param {number} x
  28691. * @param {number} y
  28692. * @param {number} z
  28693. */
  28694. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  28695. var temp = [x, y, z];
  28696. this.addUniform(name, temp);
  28697. };
  28698. /**
  28699. * Wrapper for addUniform.
  28700. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28701. * @param {Color3} color
  28702. */
  28703. UniformBuffer.prototype.addColor3 = function (name, color) {
  28704. var temp = new Array();
  28705. color.toArray(temp);
  28706. this.addUniform(name, temp);
  28707. };
  28708. /**
  28709. * Wrapper for addUniform.
  28710. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28711. * @param {Color3} color
  28712. * @param {number} alpha
  28713. */
  28714. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  28715. var temp = new Array();
  28716. color.toArray(temp);
  28717. temp.push(alpha);
  28718. this.addUniform(name, temp);
  28719. };
  28720. /**
  28721. * Wrapper for addUniform.
  28722. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28723. * @param {Vector3} vector
  28724. */
  28725. UniformBuffer.prototype.addVector3 = function (name, vector) {
  28726. var temp = new Array();
  28727. vector.toArray(temp);
  28728. this.addUniform(name, temp);
  28729. };
  28730. /**
  28731. * Wrapper for addUniform.
  28732. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28733. */
  28734. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  28735. this.addUniform(name, 12);
  28736. };
  28737. /**
  28738. * Wrapper for addUniform.
  28739. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28740. */
  28741. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  28742. this.addUniform(name, 8);
  28743. };
  28744. /**
  28745. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  28746. */
  28747. UniformBuffer.prototype.create = function () {
  28748. if (this._noUBO) {
  28749. return;
  28750. }
  28751. if (this._buffer) {
  28752. return; // nothing to do
  28753. }
  28754. // See spec, alignment must be filled as a vec4
  28755. this._fillAlignment(4);
  28756. this._bufferData = new Float32Array(this._data);
  28757. this._rebuild();
  28758. this._needSync = true;
  28759. };
  28760. UniformBuffer.prototype._rebuild = function () {
  28761. if (this._noUBO) {
  28762. return;
  28763. }
  28764. if (this._dynamic) {
  28765. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  28766. }
  28767. else {
  28768. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  28769. }
  28770. };
  28771. /**
  28772. * Updates the WebGL Uniform Buffer on the GPU.
  28773. * If the `dynamic` flag is set to true, no cache comparison is done.
  28774. * Otherwise, the buffer will be updated only if the cache differs.
  28775. */
  28776. UniformBuffer.prototype.update = function () {
  28777. if (!this._buffer) {
  28778. this.create();
  28779. return;
  28780. }
  28781. if (!this._dynamic && !this._needSync) {
  28782. return;
  28783. }
  28784. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  28785. this._needSync = false;
  28786. };
  28787. /**
  28788. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  28789. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  28790. * @param {number[]|Float32Array} data Flattened data
  28791. * @param {number} size Size of the data.
  28792. */
  28793. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  28794. var location = this._uniformLocations[uniformName];
  28795. if (location === undefined) {
  28796. if (this._buffer) {
  28797. // Cannot add an uniform if the buffer is already created
  28798. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  28799. return;
  28800. }
  28801. this.addUniform(uniformName, size);
  28802. location = this._uniformLocations[uniformName];
  28803. }
  28804. if (!this._buffer) {
  28805. this.create();
  28806. }
  28807. if (!this._dynamic) {
  28808. // Cache for static uniform buffers
  28809. var changed = false;
  28810. for (var i = 0; i < size; i++) {
  28811. if (this._bufferData[location + i] !== data[i]) {
  28812. changed = true;
  28813. this._bufferData[location + i] = data[i];
  28814. }
  28815. }
  28816. this._needSync = this._needSync || changed;
  28817. }
  28818. else {
  28819. // No cache for dynamic
  28820. for (var i = 0; i < size; i++) {
  28821. this._bufferData[location + i] = data[i];
  28822. }
  28823. }
  28824. };
  28825. // Update methods
  28826. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  28827. // To match std140, matrix must be realigned
  28828. for (var i = 0; i < 3; i++) {
  28829. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  28830. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  28831. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  28832. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  28833. }
  28834. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  28835. };
  28836. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  28837. this._currentEffect.setMatrix3x3(name, matrix);
  28838. };
  28839. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  28840. this._currentEffect.setMatrix2x2(name, matrix);
  28841. };
  28842. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  28843. // To match std140, matrix must be realigned
  28844. for (var i = 0; i < 2; i++) {
  28845. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  28846. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  28847. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  28848. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  28849. }
  28850. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  28851. };
  28852. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  28853. this._currentEffect.setFloat(name, x);
  28854. };
  28855. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  28856. UniformBuffer._tempBuffer[0] = x;
  28857. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  28858. };
  28859. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  28860. if (suffix === void 0) { suffix = ""; }
  28861. this._currentEffect.setFloat2(name + suffix, x, y);
  28862. };
  28863. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  28864. if (suffix === void 0) { suffix = ""; }
  28865. UniformBuffer._tempBuffer[0] = x;
  28866. UniformBuffer._tempBuffer[1] = y;
  28867. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  28868. };
  28869. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  28870. if (suffix === void 0) { suffix = ""; }
  28871. this._currentEffect.setFloat3(name + suffix, x, y, z);
  28872. };
  28873. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  28874. if (suffix === void 0) { suffix = ""; }
  28875. UniformBuffer._tempBuffer[0] = x;
  28876. UniformBuffer._tempBuffer[1] = y;
  28877. UniformBuffer._tempBuffer[2] = z;
  28878. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28879. };
  28880. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  28881. if (suffix === void 0) { suffix = ""; }
  28882. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  28883. };
  28884. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  28885. if (suffix === void 0) { suffix = ""; }
  28886. UniformBuffer._tempBuffer[0] = x;
  28887. UniformBuffer._tempBuffer[1] = y;
  28888. UniformBuffer._tempBuffer[2] = z;
  28889. UniformBuffer._tempBuffer[3] = w;
  28890. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28891. };
  28892. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  28893. this._currentEffect.setMatrix(name, mat);
  28894. };
  28895. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  28896. this.updateUniform(name, mat.toArray(), 16);
  28897. };
  28898. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  28899. this._currentEffect.setVector3(name, vector);
  28900. };
  28901. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  28902. vector.toArray(UniformBuffer._tempBuffer);
  28903. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28904. };
  28905. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  28906. this._currentEffect.setVector4(name, vector);
  28907. };
  28908. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  28909. vector.toArray(UniformBuffer._tempBuffer);
  28910. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28911. };
  28912. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  28913. if (suffix === void 0) { suffix = ""; }
  28914. this._currentEffect.setColor3(name + suffix, color);
  28915. };
  28916. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  28917. if (suffix === void 0) { suffix = ""; }
  28918. color.toArray(UniformBuffer._tempBuffer);
  28919. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28920. };
  28921. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  28922. if (suffix === void 0) { suffix = ""; }
  28923. this._currentEffect.setColor4(name + suffix, color, alpha);
  28924. };
  28925. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  28926. if (suffix === void 0) { suffix = ""; }
  28927. color.toArray(UniformBuffer._tempBuffer);
  28928. UniformBuffer._tempBuffer[3] = alpha;
  28929. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28930. };
  28931. /**
  28932. * Sets a sampler uniform on the effect.
  28933. * @param {string} name Name of the sampler.
  28934. * @param {Texture} texture
  28935. */
  28936. UniformBuffer.prototype.setTexture = function (name, texture) {
  28937. this._currentEffect.setTexture(name, texture);
  28938. };
  28939. /**
  28940. * Directly updates the value of the uniform in the cache AND on the GPU.
  28941. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  28942. * @param {number[]|Float32Array} data Flattened data
  28943. */
  28944. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  28945. this.updateUniform(uniformName, data, data.length);
  28946. this.update();
  28947. };
  28948. /**
  28949. * Binds this uniform buffer to an effect.
  28950. * @param {Effect} effect
  28951. * @param {string} name Name of the uniform block in the shader.
  28952. */
  28953. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  28954. this._currentEffect = effect;
  28955. if (this._noUBO || !this._buffer) {
  28956. return;
  28957. }
  28958. effect.bindUniformBuffer(this._buffer, name);
  28959. };
  28960. /**
  28961. * Disposes the uniform buffer.
  28962. */
  28963. UniformBuffer.prototype.dispose = function () {
  28964. if (this._noUBO) {
  28965. return;
  28966. }
  28967. var index = this._engine._uniformBuffers.indexOf(this);
  28968. if (index !== -1) {
  28969. this._engine._uniformBuffers.splice(index, 1);
  28970. }
  28971. if (!this._buffer) {
  28972. return;
  28973. }
  28974. if (this._engine._releaseBuffer(this._buffer)) {
  28975. this._buffer = null;
  28976. }
  28977. };
  28978. // Pool for avoiding memory leaks
  28979. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  28980. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  28981. return UniformBuffer;
  28982. }());
  28983. BABYLON.UniformBuffer = UniformBuffer;
  28984. })(BABYLON || (BABYLON = {}));
  28985. //# sourceMappingURL=babylon.uniformBuffer.js.map
  28986. var BABYLON;
  28987. (function (BABYLON) {
  28988. var VertexData = /** @class */ (function () {
  28989. function VertexData() {
  28990. }
  28991. VertexData.prototype.set = function (data, kind) {
  28992. switch (kind) {
  28993. case BABYLON.VertexBuffer.PositionKind:
  28994. this.positions = data;
  28995. break;
  28996. case BABYLON.VertexBuffer.NormalKind:
  28997. this.normals = data;
  28998. break;
  28999. case BABYLON.VertexBuffer.TangentKind:
  29000. this.tangents = data;
  29001. break;
  29002. case BABYLON.VertexBuffer.UVKind:
  29003. this.uvs = data;
  29004. break;
  29005. case BABYLON.VertexBuffer.UV2Kind:
  29006. this.uvs2 = data;
  29007. break;
  29008. case BABYLON.VertexBuffer.UV3Kind:
  29009. this.uvs3 = data;
  29010. break;
  29011. case BABYLON.VertexBuffer.UV4Kind:
  29012. this.uvs4 = data;
  29013. break;
  29014. case BABYLON.VertexBuffer.UV5Kind:
  29015. this.uvs5 = data;
  29016. break;
  29017. case BABYLON.VertexBuffer.UV6Kind:
  29018. this.uvs6 = data;
  29019. break;
  29020. case BABYLON.VertexBuffer.ColorKind:
  29021. this.colors = data;
  29022. break;
  29023. case BABYLON.VertexBuffer.MatricesIndicesKind:
  29024. this.matricesIndices = data;
  29025. break;
  29026. case BABYLON.VertexBuffer.MatricesWeightsKind:
  29027. this.matricesWeights = data;
  29028. break;
  29029. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  29030. this.matricesIndicesExtra = data;
  29031. break;
  29032. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  29033. this.matricesWeightsExtra = data;
  29034. break;
  29035. }
  29036. };
  29037. /**
  29038. * Associates the vertexData to the passed Mesh.
  29039. * Sets it as updatable or not (default `false`).
  29040. * Returns the VertexData.
  29041. */
  29042. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  29043. this._applyTo(mesh, updatable);
  29044. return this;
  29045. };
  29046. /**
  29047. * Associates the vertexData to the passed Geometry.
  29048. * Sets it as updatable or not (default `false`).
  29049. * Returns the VertexData.
  29050. */
  29051. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  29052. this._applyTo(geometry, updatable);
  29053. return this;
  29054. };
  29055. /**
  29056. * Updates the associated mesh.
  29057. * Returns the VertexData.
  29058. */
  29059. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  29060. this._update(mesh);
  29061. return this;
  29062. };
  29063. /**
  29064. * Updates the associated geometry.
  29065. * Returns the VertexData.
  29066. */
  29067. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  29068. this._update(geometry);
  29069. return this;
  29070. };
  29071. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  29072. if (updatable === void 0) { updatable = false; }
  29073. if (this.positions) {
  29074. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  29075. }
  29076. if (this.normals) {
  29077. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  29078. }
  29079. if (this.tangents) {
  29080. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  29081. }
  29082. if (this.uvs) {
  29083. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  29084. }
  29085. if (this.uvs2) {
  29086. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  29087. }
  29088. if (this.uvs3) {
  29089. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  29090. }
  29091. if (this.uvs4) {
  29092. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  29093. }
  29094. if (this.uvs5) {
  29095. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  29096. }
  29097. if (this.uvs6) {
  29098. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  29099. }
  29100. if (this.colors) {
  29101. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  29102. }
  29103. if (this.matricesIndices) {
  29104. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  29105. }
  29106. if (this.matricesWeights) {
  29107. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  29108. }
  29109. if (this.matricesIndicesExtra) {
  29110. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  29111. }
  29112. if (this.matricesWeightsExtra) {
  29113. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  29114. }
  29115. if (this.indices) {
  29116. meshOrGeometry.setIndices(this.indices, null, updatable);
  29117. }
  29118. return this;
  29119. };
  29120. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  29121. if (this.positions) {
  29122. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  29123. }
  29124. if (this.normals) {
  29125. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  29126. }
  29127. if (this.tangents) {
  29128. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  29129. }
  29130. if (this.uvs) {
  29131. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  29132. }
  29133. if (this.uvs2) {
  29134. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  29135. }
  29136. if (this.uvs3) {
  29137. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  29138. }
  29139. if (this.uvs4) {
  29140. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  29141. }
  29142. if (this.uvs5) {
  29143. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  29144. }
  29145. if (this.uvs6) {
  29146. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  29147. }
  29148. if (this.colors) {
  29149. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  29150. }
  29151. if (this.matricesIndices) {
  29152. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  29153. }
  29154. if (this.matricesWeights) {
  29155. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  29156. }
  29157. if (this.matricesIndicesExtra) {
  29158. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  29159. }
  29160. if (this.matricesWeightsExtra) {
  29161. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  29162. }
  29163. if (this.indices) {
  29164. meshOrGeometry.setIndices(this.indices, null);
  29165. }
  29166. return this;
  29167. };
  29168. /**
  29169. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  29170. * Returns the VertexData.
  29171. */
  29172. VertexData.prototype.transform = function (matrix) {
  29173. var transformed = BABYLON.Vector3.Zero();
  29174. var index;
  29175. if (this.positions) {
  29176. var position = BABYLON.Vector3.Zero();
  29177. for (index = 0; index < this.positions.length; index += 3) {
  29178. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  29179. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  29180. this.positions[index] = transformed.x;
  29181. this.positions[index + 1] = transformed.y;
  29182. this.positions[index + 2] = transformed.z;
  29183. }
  29184. }
  29185. if (this.normals) {
  29186. var normal = BABYLON.Vector3.Zero();
  29187. for (index = 0; index < this.normals.length; index += 3) {
  29188. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  29189. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  29190. this.normals[index] = transformed.x;
  29191. this.normals[index + 1] = transformed.y;
  29192. this.normals[index + 2] = transformed.z;
  29193. }
  29194. }
  29195. if (this.tangents) {
  29196. var tangent = BABYLON.Vector4.Zero();
  29197. var tangentTransformed = BABYLON.Vector4.Zero();
  29198. for (index = 0; index < this.tangents.length; index += 4) {
  29199. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  29200. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  29201. this.tangents[index] = tangentTransformed.x;
  29202. this.tangents[index + 1] = tangentTransformed.y;
  29203. this.tangents[index + 2] = tangentTransformed.z;
  29204. this.tangents[index + 3] = tangentTransformed.w;
  29205. }
  29206. }
  29207. return this;
  29208. };
  29209. /**
  29210. * Merges the passed VertexData into the current one.
  29211. * Returns the modified VertexData.
  29212. */
  29213. VertexData.prototype.merge = function (other, options) {
  29214. options = options || {};
  29215. if (other.indices) {
  29216. if (!this.indices) {
  29217. this.indices = [];
  29218. }
  29219. var offset = this.positions ? this.positions.length / 3 : 0;
  29220. for (var index = 0; index < other.indices.length; index++) {
  29221. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  29222. this.indices.push(other.indices[index] + offset);
  29223. }
  29224. }
  29225. this.positions = this._mergeElement(this.positions, other.positions);
  29226. if (!this.positions) {
  29227. return this;
  29228. }
  29229. var count = this.positions.length / 3;
  29230. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  29231. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  29232. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  29233. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  29234. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  29235. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  29236. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  29237. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  29238. this.colors = this._mergeElement(this.colors, other.colors, count * 4, 1);
  29239. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  29240. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  29241. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  29242. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  29243. return this;
  29244. };
  29245. VertexData.prototype._mergeElement = function (source, other, length, defaultValue) {
  29246. if (length === void 0) { length = 0; }
  29247. if (defaultValue === void 0) { defaultValue = 0; }
  29248. if (!other && !source) {
  29249. return null;
  29250. }
  29251. if (!other) {
  29252. var padding = new Float32Array(source.length);
  29253. padding.fill(defaultValue);
  29254. return this._mergeElement(source, padding, length);
  29255. }
  29256. if (!source) {
  29257. if (length === 0 || length === other.length) {
  29258. return other;
  29259. }
  29260. var padding = new Float32Array(length - other.length);
  29261. padding.fill(defaultValue);
  29262. return this._mergeElement(padding, other, length);
  29263. }
  29264. var len = other.length + source.length;
  29265. var isSrcTypedArray = source instanceof Float32Array;
  29266. var isOthTypedArray = other instanceof Float32Array;
  29267. // use non-loop method when the source is Float32Array
  29268. if (isSrcTypedArray) {
  29269. var ret32 = new Float32Array(len);
  29270. ret32.set(source);
  29271. ret32.set(other, source.length);
  29272. return ret32;
  29273. // source is number[], when other is also use concat
  29274. }
  29275. else if (!isOthTypedArray) {
  29276. return source.concat(other);
  29277. // source is a number[], but other is a Float32Array, loop required
  29278. }
  29279. else {
  29280. var ret = source.slice(0); // copy source to a separate array
  29281. for (var i = 0, len = other.length; i < len; i++) {
  29282. ret.push(other[i]);
  29283. }
  29284. return ret;
  29285. }
  29286. };
  29287. /**
  29288. * Serializes the VertexData.
  29289. * Returns a serialized object.
  29290. */
  29291. VertexData.prototype.serialize = function () {
  29292. var serializationObject = this.serialize();
  29293. if (this.positions) {
  29294. serializationObject.positions = this.positions;
  29295. }
  29296. if (this.normals) {
  29297. serializationObject.normals = this.normals;
  29298. }
  29299. if (this.tangents) {
  29300. serializationObject.tangents = this.tangents;
  29301. }
  29302. if (this.uvs) {
  29303. serializationObject.uvs = this.uvs;
  29304. }
  29305. if (this.uvs2) {
  29306. serializationObject.uvs2 = this.uvs2;
  29307. }
  29308. if (this.uvs3) {
  29309. serializationObject.uvs3 = this.uvs3;
  29310. }
  29311. if (this.uvs4) {
  29312. serializationObject.uvs4 = this.uvs4;
  29313. }
  29314. if (this.uvs5) {
  29315. serializationObject.uvs5 = this.uvs5;
  29316. }
  29317. if (this.uvs6) {
  29318. serializationObject.uvs6 = this.uvs6;
  29319. }
  29320. if (this.colors) {
  29321. serializationObject.colors = this.colors;
  29322. }
  29323. if (this.matricesIndices) {
  29324. serializationObject.matricesIndices = this.matricesIndices;
  29325. serializationObject.matricesIndices._isExpanded = true;
  29326. }
  29327. if (this.matricesWeights) {
  29328. serializationObject.matricesWeights = this.matricesWeights;
  29329. }
  29330. if (this.matricesIndicesExtra) {
  29331. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  29332. serializationObject.matricesIndicesExtra._isExpanded = true;
  29333. }
  29334. if (this.matricesWeightsExtra) {
  29335. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  29336. }
  29337. serializationObject.indices = this.indices;
  29338. return serializationObject;
  29339. };
  29340. // Statics
  29341. /**
  29342. * Returns the object VertexData associated to the passed mesh.
  29343. */
  29344. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  29345. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  29346. };
  29347. /**
  29348. * Returns the object VertexData associated to the passed geometry.
  29349. */
  29350. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  29351. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  29352. };
  29353. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  29354. var result = new VertexData();
  29355. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29356. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  29357. }
  29358. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29359. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  29360. }
  29361. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  29362. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  29363. }
  29364. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29365. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  29366. }
  29367. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29368. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  29369. }
  29370. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29371. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  29372. }
  29373. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29374. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  29375. }
  29376. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29377. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  29378. }
  29379. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29380. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  29381. }
  29382. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29383. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  29384. }
  29385. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29386. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  29387. }
  29388. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29389. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  29390. }
  29391. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  29392. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  29393. }
  29394. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  29395. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  29396. }
  29397. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  29398. return result;
  29399. };
  29400. /**
  29401. * Creates the vertexData of the Ribbon.
  29402. */
  29403. VertexData.CreateRibbon = function (options) {
  29404. var pathArray = options.pathArray;
  29405. var closeArray = options.closeArray || false;
  29406. var closePath = options.closePath || false;
  29407. var invertUV = options.invertUV || false;
  29408. var defaultOffset = Math.floor(pathArray[0].length / 2);
  29409. var offset = options.offset || defaultOffset;
  29410. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  29411. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29412. var customUV = options.uvs;
  29413. var customColors = options.colors;
  29414. var positions = [];
  29415. var indices = [];
  29416. var normals = [];
  29417. var uvs = [];
  29418. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  29419. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  29420. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  29421. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  29422. var minlg; // minimal length among all paths from pathArray
  29423. var lg = []; // array of path lengths : nb of vertex per path
  29424. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  29425. var p; // path iterator
  29426. var i; // point iterator
  29427. var j; // point iterator
  29428. // if single path in pathArray
  29429. if (pathArray.length < 2) {
  29430. var ar1 = [];
  29431. var ar2 = [];
  29432. for (i = 0; i < pathArray[0].length - offset; i++) {
  29433. ar1.push(pathArray[0][i]);
  29434. ar2.push(pathArray[0][i + offset]);
  29435. }
  29436. pathArray = [ar1, ar2];
  29437. }
  29438. // positions and horizontal distances (u)
  29439. var idc = 0;
  29440. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  29441. var path;
  29442. var l;
  29443. minlg = pathArray[0].length;
  29444. var vectlg;
  29445. var dist;
  29446. for (p = 0; p < pathArray.length; p++) {
  29447. uTotalDistance[p] = 0;
  29448. us[p] = [0];
  29449. path = pathArray[p];
  29450. l = path.length;
  29451. minlg = (minlg < l) ? minlg : l;
  29452. j = 0;
  29453. while (j < l) {
  29454. positions.push(path[j].x, path[j].y, path[j].z);
  29455. if (j > 0) {
  29456. vectlg = path[j].subtract(path[j - 1]).length();
  29457. dist = vectlg + uTotalDistance[p];
  29458. us[p].push(dist);
  29459. uTotalDistance[p] = dist;
  29460. }
  29461. j++;
  29462. }
  29463. if (closePath) {
  29464. j--;
  29465. positions.push(path[0].x, path[0].y, path[0].z);
  29466. vectlg = path[j].subtract(path[0]).length();
  29467. dist = vectlg + uTotalDistance[p];
  29468. us[p].push(dist);
  29469. uTotalDistance[p] = dist;
  29470. }
  29471. lg[p] = l + closePathCorr;
  29472. idx[p] = idc;
  29473. idc += (l + closePathCorr);
  29474. }
  29475. // vertical distances (v)
  29476. var path1;
  29477. var path2;
  29478. var vertex1 = null;
  29479. var vertex2 = null;
  29480. for (i = 0; i < minlg + closePathCorr; i++) {
  29481. vTotalDistance[i] = 0;
  29482. vs[i] = [0];
  29483. for (p = 0; p < pathArray.length - 1; p++) {
  29484. path1 = pathArray[p];
  29485. path2 = pathArray[p + 1];
  29486. if (i === minlg) {
  29487. vertex1 = path1[0];
  29488. vertex2 = path2[0];
  29489. }
  29490. else {
  29491. vertex1 = path1[i];
  29492. vertex2 = path2[i];
  29493. }
  29494. vectlg = vertex2.subtract(vertex1).length();
  29495. dist = vectlg + vTotalDistance[i];
  29496. vs[i].push(dist);
  29497. vTotalDistance[i] = dist;
  29498. }
  29499. if (closeArray && vertex2 && vertex1) {
  29500. path1 = pathArray[p];
  29501. path2 = pathArray[0];
  29502. if (i === minlg) {
  29503. vertex2 = path2[0];
  29504. }
  29505. vectlg = vertex2.subtract(vertex1).length();
  29506. dist = vectlg + vTotalDistance[i];
  29507. vTotalDistance[i] = dist;
  29508. }
  29509. }
  29510. // uvs
  29511. var u;
  29512. var v;
  29513. if (customUV) {
  29514. for (p = 0; p < customUV.length; p++) {
  29515. uvs.push(customUV[p].x, customUV[p].y);
  29516. }
  29517. }
  29518. else {
  29519. for (p = 0; p < pathArray.length; p++) {
  29520. for (i = 0; i < minlg + closePathCorr; i++) {
  29521. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  29522. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  29523. if (invertUV) {
  29524. uvs.push(v, u);
  29525. }
  29526. else {
  29527. uvs.push(u, v);
  29528. }
  29529. }
  29530. }
  29531. }
  29532. // indices
  29533. p = 0; // path index
  29534. var pi = 0; // positions array index
  29535. var l1 = lg[p] - 1; // path1 length
  29536. var l2 = lg[p + 1] - 1; // path2 length
  29537. var min = (l1 < l2) ? l1 : l2; // current path stop index
  29538. var shft = idx[1] - idx[0]; // shift
  29539. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  29540. while (pi <= min && p < path1nb) {
  29541. // 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
  29542. indices.push(pi, pi + shft, pi + 1);
  29543. indices.push(pi + shft + 1, pi + 1, pi + shft);
  29544. pi += 1;
  29545. if (pi === min) {
  29546. p++;
  29547. if (p === lg.length - 1) {
  29548. shft = idx[0] - idx[p];
  29549. l1 = lg[p] - 1;
  29550. l2 = lg[0] - 1;
  29551. }
  29552. else {
  29553. shft = idx[p + 1] - idx[p];
  29554. l1 = lg[p] - 1;
  29555. l2 = lg[p + 1] - 1;
  29556. }
  29557. pi = idx[p];
  29558. min = (l1 < l2) ? l1 + pi : l2 + pi;
  29559. }
  29560. }
  29561. // normals
  29562. VertexData.ComputeNormals(positions, indices, normals);
  29563. if (closePath) {
  29564. var indexFirst = 0;
  29565. var indexLast = 0;
  29566. for (p = 0; p < pathArray.length; p++) {
  29567. indexFirst = idx[p] * 3;
  29568. if (p + 1 < pathArray.length) {
  29569. indexLast = (idx[p + 1] - 1) * 3;
  29570. }
  29571. else {
  29572. indexLast = normals.length - 3;
  29573. }
  29574. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  29575. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  29576. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  29577. normals[indexLast] = normals[indexFirst];
  29578. normals[indexLast + 1] = normals[indexFirst + 1];
  29579. normals[indexLast + 2] = normals[indexFirst + 2];
  29580. }
  29581. }
  29582. // sides
  29583. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29584. // Colors
  29585. var colors = null;
  29586. if (customColors) {
  29587. colors = new Float32Array(customColors.length * 4);
  29588. for (var c = 0; c < customColors.length; c++) {
  29589. colors[c * 4] = customColors[c].r;
  29590. colors[c * 4 + 1] = customColors[c].g;
  29591. colors[c * 4 + 2] = customColors[c].b;
  29592. colors[c * 4 + 3] = customColors[c].a;
  29593. }
  29594. }
  29595. // Result
  29596. var vertexData = new VertexData();
  29597. var positions32 = new Float32Array(positions);
  29598. var normals32 = new Float32Array(normals);
  29599. var uvs32 = new Float32Array(uvs);
  29600. vertexData.indices = indices;
  29601. vertexData.positions = positions32;
  29602. vertexData.normals = normals32;
  29603. vertexData.uvs = uvs32;
  29604. if (colors) {
  29605. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  29606. }
  29607. if (closePath) {
  29608. vertexData._idx = idx;
  29609. }
  29610. return vertexData;
  29611. };
  29612. /**
  29613. * Creates the VertexData of the Box.
  29614. */
  29615. VertexData.CreateBox = function (options) {
  29616. var normalsSource = [
  29617. new BABYLON.Vector3(0, 0, 1),
  29618. new BABYLON.Vector3(0, 0, -1),
  29619. new BABYLON.Vector3(1, 0, 0),
  29620. new BABYLON.Vector3(-1, 0, 0),
  29621. new BABYLON.Vector3(0, 1, 0),
  29622. new BABYLON.Vector3(0, -1, 0)
  29623. ];
  29624. var indices = [];
  29625. var positions = [];
  29626. var normals = [];
  29627. var uvs = [];
  29628. var width = options.width || options.size || 1;
  29629. var height = options.height || options.size || 1;
  29630. var depth = options.depth || options.size || 1;
  29631. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29632. var faceUV = options.faceUV || new Array(6);
  29633. var faceColors = options.faceColors;
  29634. var colors = [];
  29635. // default face colors and UV if undefined
  29636. for (var f = 0; f < 6; f++) {
  29637. if (faceUV[f] === undefined) {
  29638. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29639. }
  29640. if (faceColors && faceColors[f] === undefined) {
  29641. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29642. }
  29643. }
  29644. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  29645. // Create each face in turn.
  29646. for (var index = 0; index < normalsSource.length; index++) {
  29647. var normal = normalsSource[index];
  29648. // Get two vectors perpendicular to the face normal and to each other.
  29649. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  29650. var side2 = BABYLON.Vector3.Cross(normal, side1);
  29651. // Six indices (two triangles) per face.
  29652. var verticesLength = positions.length / 3;
  29653. indices.push(verticesLength);
  29654. indices.push(verticesLength + 1);
  29655. indices.push(verticesLength + 2);
  29656. indices.push(verticesLength);
  29657. indices.push(verticesLength + 2);
  29658. indices.push(verticesLength + 3);
  29659. // Four vertices per face.
  29660. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  29661. positions.push(vertex.x, vertex.y, vertex.z);
  29662. normals.push(normal.x, normal.y, normal.z);
  29663. uvs.push(faceUV[index].z, faceUV[index].w);
  29664. if (faceColors) {
  29665. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29666. }
  29667. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  29668. positions.push(vertex.x, vertex.y, vertex.z);
  29669. normals.push(normal.x, normal.y, normal.z);
  29670. uvs.push(faceUV[index].x, faceUV[index].w);
  29671. if (faceColors) {
  29672. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29673. }
  29674. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  29675. positions.push(vertex.x, vertex.y, vertex.z);
  29676. normals.push(normal.x, normal.y, normal.z);
  29677. uvs.push(faceUV[index].x, faceUV[index].y);
  29678. if (faceColors) {
  29679. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29680. }
  29681. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  29682. positions.push(vertex.x, vertex.y, vertex.z);
  29683. normals.push(normal.x, normal.y, normal.z);
  29684. uvs.push(faceUV[index].z, faceUV[index].y);
  29685. if (faceColors) {
  29686. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29687. }
  29688. }
  29689. // sides
  29690. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29691. // Result
  29692. var vertexData = new VertexData();
  29693. vertexData.indices = indices;
  29694. vertexData.positions = positions;
  29695. vertexData.normals = normals;
  29696. vertexData.uvs = uvs;
  29697. if (faceColors) {
  29698. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  29699. vertexData.colors = totalColors;
  29700. }
  29701. return vertexData;
  29702. };
  29703. /**
  29704. * Creates the VertexData of the Sphere.
  29705. */
  29706. VertexData.CreateSphere = function (options) {
  29707. var segments = options.segments || 32;
  29708. var diameterX = options.diameterX || options.diameter || 1;
  29709. var diameterY = options.diameterY || options.diameter || 1;
  29710. var diameterZ = options.diameterZ || options.diameter || 1;
  29711. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29712. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  29713. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29714. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  29715. var totalZRotationSteps = 2 + segments;
  29716. var totalYRotationSteps = 2 * totalZRotationSteps;
  29717. var indices = [];
  29718. var positions = [];
  29719. var normals = [];
  29720. var uvs = [];
  29721. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  29722. var normalizedZ = zRotationStep / totalZRotationSteps;
  29723. var angleZ = normalizedZ * Math.PI * slice;
  29724. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  29725. var normalizedY = yRotationStep / totalYRotationSteps;
  29726. var angleY = normalizedY * Math.PI * 2 * arc;
  29727. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  29728. var rotationY = BABYLON.Matrix.RotationY(angleY);
  29729. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  29730. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  29731. var vertex = complete.multiply(radius);
  29732. var normal = complete.divide(radius).normalize();
  29733. positions.push(vertex.x, vertex.y, vertex.z);
  29734. normals.push(normal.x, normal.y, normal.z);
  29735. uvs.push(normalizedY, normalizedZ);
  29736. }
  29737. if (zRotationStep > 0) {
  29738. var verticesCount = positions.length / 3;
  29739. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  29740. indices.push((firstIndex));
  29741. indices.push((firstIndex + 1));
  29742. indices.push(firstIndex + totalYRotationSteps + 1);
  29743. indices.push((firstIndex + totalYRotationSteps + 1));
  29744. indices.push((firstIndex + 1));
  29745. indices.push((firstIndex + totalYRotationSteps + 2));
  29746. }
  29747. }
  29748. }
  29749. // Sides
  29750. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29751. // Result
  29752. var vertexData = new VertexData();
  29753. vertexData.indices = indices;
  29754. vertexData.positions = positions;
  29755. vertexData.normals = normals;
  29756. vertexData.uvs = uvs;
  29757. return vertexData;
  29758. };
  29759. /**
  29760. * Creates the VertexData of the Cylinder or Cone.
  29761. */
  29762. VertexData.CreateCylinder = function (options) {
  29763. var height = options.height || 2;
  29764. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  29765. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  29766. var tessellation = options.tessellation || 24;
  29767. var subdivisions = options.subdivisions || 1;
  29768. var hasRings = options.hasRings ? true : false;
  29769. var enclose = options.enclose ? true : false;
  29770. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29771. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29772. var faceUV = options.faceUV || new Array(3);
  29773. var faceColors = options.faceColors;
  29774. // default face colors and UV if undefined
  29775. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  29776. var ringNb = (hasRings) ? subdivisions : 1;
  29777. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  29778. var f;
  29779. for (f = 0; f < surfaceNb; f++) {
  29780. if (faceColors && faceColors[f] === undefined) {
  29781. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29782. }
  29783. }
  29784. for (f = 0; f < surfaceNb; f++) {
  29785. if (faceUV && faceUV[f] === undefined) {
  29786. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29787. }
  29788. }
  29789. var indices = new Array();
  29790. var positions = new Array();
  29791. var normals = new Array();
  29792. var uvs = new Array();
  29793. var colors = new Array();
  29794. var angle_step = Math.PI * 2 * arc / tessellation;
  29795. var angle;
  29796. var h;
  29797. var radius;
  29798. var tan = (diameterBottom - diameterTop) / 2 / height;
  29799. var ringVertex = BABYLON.Vector3.Zero();
  29800. var ringNormal = BABYLON.Vector3.Zero();
  29801. var ringFirstVertex = BABYLON.Vector3.Zero();
  29802. var ringFirstNormal = BABYLON.Vector3.Zero();
  29803. var quadNormal = BABYLON.Vector3.Zero();
  29804. var Y = BABYLON.Axis.Y;
  29805. // positions, normals, uvs
  29806. var i;
  29807. var j;
  29808. var r;
  29809. var ringIdx = 1;
  29810. var s = 1; // surface index
  29811. var cs = 0;
  29812. var v = 0;
  29813. for (i = 0; i <= subdivisions; i++) {
  29814. h = i / subdivisions;
  29815. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  29816. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  29817. for (r = 0; r < ringIdx; r++) {
  29818. if (hasRings) {
  29819. s += r;
  29820. }
  29821. if (enclose) {
  29822. s += 2 * r;
  29823. }
  29824. for (j = 0; j <= tessellation; j++) {
  29825. angle = j * angle_step;
  29826. // position
  29827. ringVertex.x = Math.cos(-angle) * radius;
  29828. ringVertex.y = -height / 2 + h * height;
  29829. ringVertex.z = Math.sin(-angle) * radius;
  29830. // normal
  29831. if (diameterTop === 0 && i === subdivisions) {
  29832. // if no top cap, reuse former normals
  29833. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  29834. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  29835. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  29836. }
  29837. else {
  29838. ringNormal.x = ringVertex.x;
  29839. ringNormal.z = ringVertex.z;
  29840. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  29841. ringNormal.normalize();
  29842. }
  29843. // keep first ring vertex values for enclose
  29844. if (j === 0) {
  29845. ringFirstVertex.copyFrom(ringVertex);
  29846. ringFirstNormal.copyFrom(ringNormal);
  29847. }
  29848. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  29849. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  29850. if (hasRings) {
  29851. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  29852. }
  29853. else {
  29854. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  29855. }
  29856. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  29857. if (faceColors) {
  29858. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  29859. }
  29860. }
  29861. // if enclose, add four vertices and their dedicated normals
  29862. if (arc !== 1 && enclose) {
  29863. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  29864. positions.push(0, ringVertex.y, 0);
  29865. positions.push(0, ringVertex.y, 0);
  29866. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  29867. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  29868. quadNormal.normalize();
  29869. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29870. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  29871. quadNormal.normalize();
  29872. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29873. if (hasRings) {
  29874. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  29875. }
  29876. else {
  29877. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  29878. }
  29879. uvs.push(faceUV[s + 1].x, v);
  29880. uvs.push(faceUV[s + 1].z, v);
  29881. if (hasRings) {
  29882. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  29883. }
  29884. else {
  29885. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  29886. }
  29887. uvs.push(faceUV[s + 2].x, v);
  29888. uvs.push(faceUV[s + 2].z, v);
  29889. if (faceColors) {
  29890. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29891. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29892. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29893. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29894. }
  29895. }
  29896. if (cs !== s) {
  29897. cs = s;
  29898. }
  29899. }
  29900. }
  29901. // indices
  29902. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  29903. var s;
  29904. i = 0;
  29905. for (s = 0; s < subdivisions; s++) {
  29906. var i0 = 0;
  29907. var i1 = 0;
  29908. var i2 = 0;
  29909. var i3 = 0;
  29910. for (j = 0; j < tessellation; j++) {
  29911. i0 = i * (e + 1) + j;
  29912. i1 = (i + 1) * (e + 1) + j;
  29913. i2 = i * (e + 1) + (j + 1);
  29914. i3 = (i + 1) * (e + 1) + (j + 1);
  29915. indices.push(i0, i1, i2);
  29916. indices.push(i3, i2, i1);
  29917. }
  29918. if (arc !== 1 && enclose) {
  29919. indices.push(i0 + 2, i1 + 2, i2 + 2);
  29920. indices.push(i3 + 2, i2 + 2, i1 + 2);
  29921. indices.push(i0 + 4, i1 + 4, i2 + 4);
  29922. indices.push(i3 + 4, i2 + 4, i1 + 4);
  29923. }
  29924. i = (hasRings) ? (i + 2) : (i + 1);
  29925. }
  29926. // Caps
  29927. var createCylinderCap = function (isTop) {
  29928. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  29929. if (radius === 0) {
  29930. return;
  29931. }
  29932. // Cap positions, normals & uvs
  29933. var angle;
  29934. var circleVector;
  29935. var i;
  29936. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  29937. var c = null;
  29938. if (faceColors) {
  29939. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  29940. }
  29941. // cap center
  29942. var vbase = positions.length / 3;
  29943. var offset = isTop ? height / 2 : -height / 2;
  29944. var center = new BABYLON.Vector3(0, offset, 0);
  29945. positions.push(center.x, center.y, center.z);
  29946. normals.push(0, isTop ? 1 : -1, 0);
  29947. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  29948. if (c) {
  29949. colors.push(c.r, c.g, c.b, c.a);
  29950. }
  29951. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  29952. for (i = 0; i <= tessellation; i++) {
  29953. angle = Math.PI * 2 * i * arc / tessellation;
  29954. var cos = Math.cos(-angle);
  29955. var sin = Math.sin(-angle);
  29956. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  29957. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  29958. positions.push(circleVector.x, circleVector.y, circleVector.z);
  29959. normals.push(0, isTop ? 1 : -1, 0);
  29960. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  29961. if (c) {
  29962. colors.push(c.r, c.g, c.b, c.a);
  29963. }
  29964. }
  29965. // Cap indices
  29966. for (i = 0; i < tessellation; i++) {
  29967. if (!isTop) {
  29968. indices.push(vbase);
  29969. indices.push(vbase + (i + 1));
  29970. indices.push(vbase + (i + 2));
  29971. }
  29972. else {
  29973. indices.push(vbase);
  29974. indices.push(vbase + (i + 2));
  29975. indices.push(vbase + (i + 1));
  29976. }
  29977. }
  29978. };
  29979. // add caps to geometry
  29980. createCylinderCap(false);
  29981. createCylinderCap(true);
  29982. // Sides
  29983. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29984. var vertexData = new VertexData();
  29985. vertexData.indices = indices;
  29986. vertexData.positions = positions;
  29987. vertexData.normals = normals;
  29988. vertexData.uvs = uvs;
  29989. if (faceColors) {
  29990. vertexData.colors = colors;
  29991. }
  29992. return vertexData;
  29993. };
  29994. /**
  29995. * Creates the VertexData of the Torus.
  29996. */
  29997. VertexData.CreateTorus = function (options) {
  29998. var indices = [];
  29999. var positions = [];
  30000. var normals = [];
  30001. var uvs = [];
  30002. var diameter = options.diameter || 1;
  30003. var thickness = options.thickness || 0.5;
  30004. var tessellation = options.tessellation || 16;
  30005. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30006. var stride = tessellation + 1;
  30007. for (var i = 0; i <= tessellation; i++) {
  30008. var u = i / tessellation;
  30009. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  30010. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  30011. for (var j = 0; j <= tessellation; j++) {
  30012. var v = 1 - j / tessellation;
  30013. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  30014. var dx = Math.cos(innerAngle);
  30015. var dy = Math.sin(innerAngle);
  30016. // Create a vertex.
  30017. var normal = new BABYLON.Vector3(dx, dy, 0);
  30018. var position = normal.scale(thickness / 2);
  30019. var textureCoordinate = new BABYLON.Vector2(u, v);
  30020. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  30021. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  30022. positions.push(position.x, position.y, position.z);
  30023. normals.push(normal.x, normal.y, normal.z);
  30024. uvs.push(textureCoordinate.x, textureCoordinate.y);
  30025. // And create indices for two triangles.
  30026. var nextI = (i + 1) % stride;
  30027. var nextJ = (j + 1) % stride;
  30028. indices.push(i * stride + j);
  30029. indices.push(i * stride + nextJ);
  30030. indices.push(nextI * stride + j);
  30031. indices.push(i * stride + nextJ);
  30032. indices.push(nextI * stride + nextJ);
  30033. indices.push(nextI * stride + j);
  30034. }
  30035. }
  30036. // Sides
  30037. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30038. // Result
  30039. var vertexData = new VertexData();
  30040. vertexData.indices = indices;
  30041. vertexData.positions = positions;
  30042. vertexData.normals = normals;
  30043. vertexData.uvs = uvs;
  30044. return vertexData;
  30045. };
  30046. /**
  30047. * Creates the VertexData of the LineSystem.
  30048. */
  30049. VertexData.CreateLineSystem = function (options) {
  30050. var indices = [];
  30051. var positions = [];
  30052. var lines = options.lines;
  30053. var colors = options.colors;
  30054. var vertexColors = [];
  30055. var idx = 0;
  30056. for (var l = 0; l < lines.length; l++) {
  30057. var points = lines[l];
  30058. for (var index = 0; index < points.length; index++) {
  30059. positions.push(points[index].x, points[index].y, points[index].z);
  30060. if (colors) {
  30061. var color = colors[l];
  30062. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  30063. }
  30064. if (index > 0) {
  30065. indices.push(idx - 1);
  30066. indices.push(idx);
  30067. }
  30068. idx++;
  30069. }
  30070. }
  30071. var vertexData = new VertexData();
  30072. vertexData.indices = indices;
  30073. vertexData.positions = positions;
  30074. if (colors) {
  30075. vertexData.colors = vertexColors;
  30076. }
  30077. return vertexData;
  30078. };
  30079. /**
  30080. * Create the VertexData of the DashedLines.
  30081. */
  30082. VertexData.CreateDashedLines = function (options) {
  30083. var dashSize = options.dashSize || 3;
  30084. var gapSize = options.gapSize || 1;
  30085. var dashNb = options.dashNb || 200;
  30086. var points = options.points;
  30087. var positions = new Array();
  30088. var indices = new Array();
  30089. var curvect = BABYLON.Vector3.Zero();
  30090. var lg = 0;
  30091. var nb = 0;
  30092. var shft = 0;
  30093. var dashshft = 0;
  30094. var curshft = 0;
  30095. var idx = 0;
  30096. var i = 0;
  30097. for (i = 0; i < points.length - 1; i++) {
  30098. points[i + 1].subtractToRef(points[i], curvect);
  30099. lg += curvect.length();
  30100. }
  30101. shft = lg / dashNb;
  30102. dashshft = dashSize * shft / (dashSize + gapSize);
  30103. for (i = 0; i < points.length - 1; i++) {
  30104. points[i + 1].subtractToRef(points[i], curvect);
  30105. nb = Math.floor(curvect.length() / shft);
  30106. curvect.normalize();
  30107. for (var j = 0; j < nb; j++) {
  30108. curshft = shft * j;
  30109. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  30110. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  30111. indices.push(idx, idx + 1);
  30112. idx += 2;
  30113. }
  30114. }
  30115. // Result
  30116. var vertexData = new VertexData();
  30117. vertexData.positions = positions;
  30118. vertexData.indices = indices;
  30119. return vertexData;
  30120. };
  30121. /**
  30122. * Creates the VertexData of the Ground.
  30123. */
  30124. VertexData.CreateGround = function (options) {
  30125. var indices = [];
  30126. var positions = [];
  30127. var normals = [];
  30128. var uvs = [];
  30129. var row, col;
  30130. var width = options.width || 1;
  30131. var height = options.height || 1;
  30132. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  30133. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  30134. for (row = 0; row <= subdivisionsY; row++) {
  30135. for (col = 0; col <= subdivisionsX; col++) {
  30136. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  30137. var normal = new BABYLON.Vector3(0, 1.0, 0);
  30138. positions.push(position.x, position.y, position.z);
  30139. normals.push(normal.x, normal.y, normal.z);
  30140. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  30141. }
  30142. }
  30143. for (row = 0; row < subdivisionsY; row++) {
  30144. for (col = 0; col < subdivisionsX; col++) {
  30145. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  30146. indices.push(col + 1 + row * (subdivisionsX + 1));
  30147. indices.push(col + row * (subdivisionsX + 1));
  30148. indices.push(col + (row + 1) * (subdivisionsX + 1));
  30149. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  30150. indices.push(col + row * (subdivisionsX + 1));
  30151. }
  30152. }
  30153. // Result
  30154. var vertexData = new VertexData();
  30155. vertexData.indices = indices;
  30156. vertexData.positions = positions;
  30157. vertexData.normals = normals;
  30158. vertexData.uvs = uvs;
  30159. return vertexData;
  30160. };
  30161. /**
  30162. * Creates the VertexData of the TiledGround.
  30163. */
  30164. VertexData.CreateTiledGround = function (options) {
  30165. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  30166. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  30167. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  30168. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  30169. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  30170. var precision = options.precision || { w: 1, h: 1 };
  30171. var indices = new Array();
  30172. var positions = new Array();
  30173. var normals = new Array();
  30174. var uvs = new Array();
  30175. var row, col, tileRow, tileCol;
  30176. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  30177. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  30178. precision.w = (precision.w < 1) ? 1 : precision.w;
  30179. precision.h = (precision.h < 1) ? 1 : precision.h;
  30180. var tileSize = {
  30181. 'w': (xmax - xmin) / subdivisions.w,
  30182. 'h': (zmax - zmin) / subdivisions.h
  30183. };
  30184. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  30185. // Indices
  30186. var base = positions.length / 3;
  30187. var rowLength = precision.w + 1;
  30188. for (row = 0; row < precision.h; row++) {
  30189. for (col = 0; col < precision.w; col++) {
  30190. var square = [
  30191. base + col + row * rowLength,
  30192. base + (col + 1) + row * rowLength,
  30193. base + (col + 1) + (row + 1) * rowLength,
  30194. base + col + (row + 1) * rowLength
  30195. ];
  30196. indices.push(square[1]);
  30197. indices.push(square[2]);
  30198. indices.push(square[3]);
  30199. indices.push(square[0]);
  30200. indices.push(square[1]);
  30201. indices.push(square[3]);
  30202. }
  30203. }
  30204. // Position, normals and uvs
  30205. var position = BABYLON.Vector3.Zero();
  30206. var normal = new BABYLON.Vector3(0, 1.0, 0);
  30207. for (row = 0; row <= precision.h; row++) {
  30208. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  30209. for (col = 0; col <= precision.w; col++) {
  30210. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  30211. position.y = 0;
  30212. positions.push(position.x, position.y, position.z);
  30213. normals.push(normal.x, normal.y, normal.z);
  30214. uvs.push(col / precision.w, row / precision.h);
  30215. }
  30216. }
  30217. }
  30218. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  30219. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  30220. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  30221. }
  30222. }
  30223. // Result
  30224. var vertexData = new VertexData();
  30225. vertexData.indices = indices;
  30226. vertexData.positions = positions;
  30227. vertexData.normals = normals;
  30228. vertexData.uvs = uvs;
  30229. return vertexData;
  30230. };
  30231. /**
  30232. * Creates the VertexData of the Ground designed from a heightmap.
  30233. */
  30234. VertexData.CreateGroundFromHeightMap = function (options) {
  30235. var indices = [];
  30236. var positions = [];
  30237. var normals = [];
  30238. var uvs = [];
  30239. var row, col;
  30240. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  30241. // Vertices
  30242. for (row = 0; row <= options.subdivisions; row++) {
  30243. for (col = 0; col <= options.subdivisions; col++) {
  30244. 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));
  30245. // Compute height
  30246. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  30247. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  30248. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  30249. var r = options.buffer[pos] / 255.0;
  30250. var g = options.buffer[pos + 1] / 255.0;
  30251. var b = options.buffer[pos + 2] / 255.0;
  30252. var gradient = r * filter.r + g * filter.g + b * filter.b;
  30253. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  30254. // Add vertex
  30255. positions.push(position.x, position.y, position.z);
  30256. normals.push(0, 0, 0);
  30257. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  30258. }
  30259. }
  30260. // Indices
  30261. for (row = 0; row < options.subdivisions; row++) {
  30262. for (col = 0; col < options.subdivisions; col++) {
  30263. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30264. indices.push(col + 1 + row * (options.subdivisions + 1));
  30265. indices.push(col + row * (options.subdivisions + 1));
  30266. indices.push(col + (row + 1) * (options.subdivisions + 1));
  30267. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30268. indices.push(col + row * (options.subdivisions + 1));
  30269. }
  30270. }
  30271. // Normals
  30272. VertexData.ComputeNormals(positions, indices, normals);
  30273. // Result
  30274. var vertexData = new VertexData();
  30275. vertexData.indices = indices;
  30276. vertexData.positions = positions;
  30277. vertexData.normals = normals;
  30278. vertexData.uvs = uvs;
  30279. return vertexData;
  30280. };
  30281. /**
  30282. * Creates the VertexData of the Plane.
  30283. */
  30284. VertexData.CreatePlane = function (options) {
  30285. var indices = [];
  30286. var positions = [];
  30287. var normals = [];
  30288. var uvs = [];
  30289. var width = options.width || options.size || 1;
  30290. var height = options.height || options.size || 1;
  30291. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30292. // Vertices
  30293. var halfWidth = width / 2.0;
  30294. var halfHeight = height / 2.0;
  30295. positions.push(-halfWidth, -halfHeight, 0);
  30296. normals.push(0, 0, -1.0);
  30297. uvs.push(0.0, 0.0);
  30298. positions.push(halfWidth, -halfHeight, 0);
  30299. normals.push(0, 0, -1.0);
  30300. uvs.push(1.0, 0.0);
  30301. positions.push(halfWidth, halfHeight, 0);
  30302. normals.push(0, 0, -1.0);
  30303. uvs.push(1.0, 1.0);
  30304. positions.push(-halfWidth, halfHeight, 0);
  30305. normals.push(0, 0, -1.0);
  30306. uvs.push(0.0, 1.0);
  30307. // Indices
  30308. indices.push(0);
  30309. indices.push(1);
  30310. indices.push(2);
  30311. indices.push(0);
  30312. indices.push(2);
  30313. indices.push(3);
  30314. // Sides
  30315. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30316. // Result
  30317. var vertexData = new VertexData();
  30318. vertexData.indices = indices;
  30319. vertexData.positions = positions;
  30320. vertexData.normals = normals;
  30321. vertexData.uvs = uvs;
  30322. return vertexData;
  30323. };
  30324. /**
  30325. * Creates the VertexData of the Disc or regular Polygon.
  30326. */
  30327. VertexData.CreateDisc = function (options) {
  30328. var positions = new Array();
  30329. var indices = new Array();
  30330. var normals = new Array();
  30331. var uvs = new Array();
  30332. var radius = options.radius || 0.5;
  30333. var tessellation = options.tessellation || 64;
  30334. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30335. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30336. // positions and uvs
  30337. positions.push(0, 0, 0); // disc center first
  30338. uvs.push(0.5, 0.5);
  30339. var theta = Math.PI * 2 * arc;
  30340. var step = theta / tessellation;
  30341. for (var a = 0; a < theta; a += step) {
  30342. var x = Math.cos(a);
  30343. var y = Math.sin(a);
  30344. var u = (x + 1) / 2;
  30345. var v = (1 - y) / 2;
  30346. positions.push(radius * x, radius * y, 0);
  30347. uvs.push(u, v);
  30348. }
  30349. if (arc === 1) {
  30350. positions.push(positions[3], positions[4], positions[5]); // close the circle
  30351. uvs.push(uvs[2], uvs[3]);
  30352. }
  30353. //indices
  30354. var vertexNb = positions.length / 3;
  30355. for (var i = 1; i < vertexNb - 1; i++) {
  30356. indices.push(i + 1, 0, i);
  30357. }
  30358. // result
  30359. VertexData.ComputeNormals(positions, indices, normals);
  30360. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30361. var vertexData = new VertexData();
  30362. vertexData.indices = indices;
  30363. vertexData.positions = positions;
  30364. vertexData.normals = normals;
  30365. vertexData.uvs = uvs;
  30366. return vertexData;
  30367. };
  30368. /**
  30369. * Re-creates the VertexData of the Polygon for sideOrientation.
  30370. */
  30371. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  30372. var faceUV = fUV || new Array(3);
  30373. var faceColors = fColors;
  30374. var colors = [];
  30375. // default face colors and UV if undefined
  30376. for (var f = 0; f < 3; f++) {
  30377. if (faceUV[f] === undefined) {
  30378. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30379. }
  30380. if (faceColors && faceColors[f] === undefined) {
  30381. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30382. }
  30383. }
  30384. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30385. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30386. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30387. var indices = polygon.getIndices();
  30388. // set face colours and textures
  30389. var idx = 0;
  30390. var face = 0;
  30391. for (var index = 0; index < normals.length; index += 3) {
  30392. //Edge Face no. 1
  30393. if (Math.abs(normals[index + 1]) < 0.001) {
  30394. face = 1;
  30395. }
  30396. //Top Face no. 0
  30397. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  30398. face = 0;
  30399. }
  30400. //Bottom Face no. 2
  30401. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  30402. face = 2;
  30403. }
  30404. idx = index / 3;
  30405. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  30406. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  30407. if (faceColors) {
  30408. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  30409. }
  30410. }
  30411. // sides
  30412. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  30413. // Result
  30414. var vertexData = new VertexData();
  30415. vertexData.indices = indices;
  30416. vertexData.positions = positions;
  30417. vertexData.normals = normals;
  30418. vertexData.uvs = uvs;
  30419. if (faceColors) {
  30420. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  30421. vertexData.colors = totalColors;
  30422. }
  30423. return vertexData;
  30424. };
  30425. /**
  30426. * Creates the VertexData of the IcoSphere.
  30427. */
  30428. VertexData.CreateIcoSphere = function (options) {
  30429. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30430. var radius = options.radius || 1;
  30431. var flat = (options.flat === undefined) ? true : options.flat;
  30432. var subdivisions = options.subdivisions || 4;
  30433. var radiusX = options.radiusX || radius;
  30434. var radiusY = options.radiusY || radius;
  30435. var radiusZ = options.radiusZ || radius;
  30436. var t = (1 + Math.sqrt(5)) / 2;
  30437. // 12 vertex x,y,z
  30438. var ico_vertices = [
  30439. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  30440. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  30441. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  30442. ];
  30443. // index of 3 vertex makes a face of icopshere
  30444. var ico_indices = [
  30445. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  30446. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  30447. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  30448. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  30449. ];
  30450. // vertex for uv have aliased position, not for UV
  30451. var vertices_unalias_id = [
  30452. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  30453. // vertex alias
  30454. 0,
  30455. 2,
  30456. 3,
  30457. 3,
  30458. 3,
  30459. 4,
  30460. 7,
  30461. 8,
  30462. 9,
  30463. 9,
  30464. 10,
  30465. 11 // 23: B + 12
  30466. ];
  30467. // uv as integer step (not pixels !)
  30468. var ico_vertexuv = [
  30469. 5, 1, 3, 1, 6, 4, 0, 0,
  30470. 5, 3, 4, 2, 2, 2, 4, 0,
  30471. 2, 0, 1, 1, 6, 0, 6, 2,
  30472. // vertex alias (for same vertex on different faces)
  30473. 0, 4,
  30474. 3, 3,
  30475. 4, 4,
  30476. 3, 1,
  30477. 4, 2,
  30478. 4, 4,
  30479. 0, 2,
  30480. 1, 1,
  30481. 2, 2,
  30482. 3, 3,
  30483. 1, 3,
  30484. 2, 4 // 23: B + 12
  30485. ];
  30486. // Vertices[0, 1, ...9, A, B] : position on UV plane
  30487. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  30488. // First island of uv mapping
  30489. // v = 4h 3+ 2
  30490. // v = 3h 9+ 4
  30491. // v = 2h 9+ 5 B
  30492. // v = 1h 9 1 0
  30493. // v = 0h 3 8 7 A
  30494. // u = 0 1 2 3 4 5 6 *a
  30495. // Second island of uv mapping
  30496. // v = 4h 0+ B+ 4+
  30497. // v = 3h A+ 2+
  30498. // v = 2h 7+ 6 3+
  30499. // v = 1h 8+ 3+
  30500. // v = 0h
  30501. // u = 0 1 2 3 4 5 6 *a
  30502. // Face layout on texture UV mapping
  30503. // ============
  30504. // \ 4 /\ 16 / ======
  30505. // \ / \ / /\ 11 /
  30506. // \/ 7 \/ / \ /
  30507. // ======= / 10 \/
  30508. // /\ 17 /\ =======
  30509. // / \ / \ \ 15 /\
  30510. // / 8 \/ 12 \ \ / \
  30511. // ============ \/ 6 \
  30512. // \ 18 /\ ============
  30513. // \ / \ \ 5 /\ 0 /
  30514. // \/ 13 \ \ / \ /
  30515. // ======= \/ 1 \/
  30516. // =============
  30517. // /\ 19 /\ 2 /\
  30518. // / \ / \ / \
  30519. // / 14 \/ 9 \/ 3 \
  30520. // ===================
  30521. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  30522. var ustep = 138 / 1024;
  30523. var vstep = 239 / 1024;
  30524. var uoffset = 60 / 1024;
  30525. var voffset = 26 / 1024;
  30526. // Second island should have margin, not to touch the first island
  30527. // avoid any borderline artefact in pixel rounding
  30528. var island_u_offset = -40 / 1024;
  30529. var island_v_offset = +20 / 1024;
  30530. // face is either island 0 or 1 :
  30531. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  30532. var island = [
  30533. 0, 0, 0, 0, 1,
  30534. 0, 0, 1, 1, 0,
  30535. 0, 0, 1, 1, 0,
  30536. 0, 1, 1, 1, 0 // 15 - 19
  30537. ];
  30538. var indices = new Array();
  30539. var positions = new Array();
  30540. var normals = new Array();
  30541. var uvs = new Array();
  30542. var current_indice = 0;
  30543. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  30544. var face_vertex_pos = new Array(3);
  30545. var face_vertex_uv = new Array(3);
  30546. var v012;
  30547. for (v012 = 0; v012 < 3; v012++) {
  30548. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  30549. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  30550. }
  30551. // create all with normals
  30552. for (var face = 0; face < 20; face++) {
  30553. // 3 vertex per face
  30554. for (v012 = 0; v012 < 3; v012++) {
  30555. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  30556. var v_id = ico_indices[3 * face + v012];
  30557. // vertex have 3D position (x,y,z)
  30558. 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]);
  30559. // Normalize to get normal, then scale to radius
  30560. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  30561. // uv Coordinates from vertex ID
  30562. 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);
  30563. }
  30564. // Subdivide the face (interpolate pos, norm, uv)
  30565. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  30566. // - norm is linear interpolation of vertex corner normal
  30567. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  30568. // - uv is linear interpolation
  30569. //
  30570. // Topology is as below for sub-divide by 2
  30571. // vertex shown as v0,v1,v2
  30572. // interp index is i1 to progress in range [v0,v1[
  30573. // interp index is i2 to progress in range [v0,v2[
  30574. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  30575. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30576. //
  30577. //
  30578. // i2 v2
  30579. // ^ ^
  30580. // / / \
  30581. // / / \
  30582. // / / \
  30583. // / / (0,1) \
  30584. // / #---------\
  30585. // / / \ (0,0)'/ \
  30586. // / / \ / \
  30587. // / / \ / \
  30588. // / / (0,0) \ / (1,0) \
  30589. // / #---------#---------\
  30590. // v0 v1
  30591. //
  30592. // --------------------> i1
  30593. //
  30594. // interp of (i1,i2):
  30595. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  30596. // along i1 : lerp(x0,x1, i1/(S-i2))
  30597. //
  30598. // centroid of triangle is needed to get help normal computation
  30599. // (c1,c2) are used for centroid location
  30600. var interp_vertex = function (i1, i2, c1, c2) {
  30601. // vertex is interpolated from
  30602. // - face_vertex_pos[0..2]
  30603. // - face_vertex_uv[0..2]
  30604. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  30605. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  30606. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  30607. pos_interp.normalize();
  30608. var vertex_normal;
  30609. if (flat) {
  30610. // in flat mode, recalculate normal as face centroid normal
  30611. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  30612. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  30613. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  30614. }
  30615. else {
  30616. // in smooth mode, recalculate normal from each single vertex position
  30617. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  30618. }
  30619. // Vertex normal need correction due to X,Y,Z radius scaling
  30620. vertex_normal.x /= radiusX;
  30621. vertex_normal.y /= radiusY;
  30622. vertex_normal.z /= radiusZ;
  30623. vertex_normal.normalize();
  30624. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  30625. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  30626. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  30627. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  30628. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  30629. uvs.push(uv_interp.x, uv_interp.y);
  30630. // push each vertex has member of a face
  30631. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  30632. indices.push(current_indice);
  30633. current_indice++;
  30634. };
  30635. for (var i2 = 0; i2 < subdivisions; i2++) {
  30636. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  30637. // face : (i1,i2) for /\ :
  30638. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  30639. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30640. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30641. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30642. if (i1 + i2 + 1 < subdivisions) {
  30643. // face : (i1,i2)' for \/ :
  30644. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30645. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30646. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30647. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30648. }
  30649. }
  30650. }
  30651. }
  30652. // Sides
  30653. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30654. // Result
  30655. var vertexData = new VertexData();
  30656. vertexData.indices = indices;
  30657. vertexData.positions = positions;
  30658. vertexData.normals = normals;
  30659. vertexData.uvs = uvs;
  30660. return vertexData;
  30661. };
  30662. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  30663. /**
  30664. * Creates the VertexData of the Polyhedron.
  30665. */
  30666. VertexData.CreatePolyhedron = function (options) {
  30667. // provided polyhedron types :
  30668. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  30669. // 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)
  30670. var polyhedra = [];
  30671. 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]] };
  30672. 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]] };
  30673. polyhedra[2] = {
  30674. 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]],
  30675. 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]]
  30676. };
  30677. polyhedra[3] = {
  30678. 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]],
  30679. 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]]
  30680. };
  30681. polyhedra[4] = {
  30682. 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]],
  30683. 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]]
  30684. };
  30685. 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]] };
  30686. 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]] };
  30687. 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]] };
  30688. 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]] };
  30689. 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]] };
  30690. 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]] };
  30691. 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]] };
  30692. 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]] };
  30693. 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]] };
  30694. polyhedra[14] = {
  30695. 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]],
  30696. 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]]
  30697. };
  30698. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  30699. var size = options.size;
  30700. var sizeX = options.sizeX || size || 1;
  30701. var sizeY = options.sizeY || size || 1;
  30702. var sizeZ = options.sizeZ || size || 1;
  30703. var data = options.custom || polyhedra[type];
  30704. var nbfaces = data.face.length;
  30705. var faceUV = options.faceUV || new Array(nbfaces);
  30706. var faceColors = options.faceColors;
  30707. var flat = (options.flat === undefined) ? true : options.flat;
  30708. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30709. var positions = new Array();
  30710. var indices = new Array();
  30711. var normals = new Array();
  30712. var uvs = new Array();
  30713. var colors = new Array();
  30714. var index = 0;
  30715. var faceIdx = 0; // face cursor in the array "indexes"
  30716. var indexes = new Array();
  30717. var i = 0;
  30718. var f = 0;
  30719. var u, v, ang, x, y, tmp;
  30720. // default face colors and UV if undefined
  30721. if (flat) {
  30722. for (f = 0; f < nbfaces; f++) {
  30723. if (faceColors && faceColors[f] === undefined) {
  30724. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30725. }
  30726. if (faceUV && faceUV[f] === undefined) {
  30727. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30728. }
  30729. }
  30730. }
  30731. if (!flat) {
  30732. for (i = 0; i < data.vertex.length; i++) {
  30733. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  30734. uvs.push(0, 0);
  30735. }
  30736. for (f = 0; f < nbfaces; f++) {
  30737. for (i = 0; i < data.face[f].length - 2; i++) {
  30738. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  30739. }
  30740. }
  30741. }
  30742. else {
  30743. for (f = 0; f < nbfaces; f++) {
  30744. var fl = data.face[f].length; // number of vertices of the current face
  30745. ang = 2 * Math.PI / fl;
  30746. x = 0.5 * Math.tan(ang / 2);
  30747. y = 0.5;
  30748. // positions, uvs, colors
  30749. for (i = 0; i < fl; i++) {
  30750. // positions
  30751. 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);
  30752. indexes.push(index);
  30753. index++;
  30754. // uvs
  30755. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  30756. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  30757. uvs.push(u, v);
  30758. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  30759. y = x * Math.sin(ang) + y * Math.cos(ang);
  30760. x = tmp;
  30761. // colors
  30762. if (faceColors) {
  30763. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  30764. }
  30765. }
  30766. // indices from indexes
  30767. for (i = 0; i < fl - 2; i++) {
  30768. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  30769. }
  30770. faceIdx += fl;
  30771. }
  30772. }
  30773. VertexData.ComputeNormals(positions, indices, normals);
  30774. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30775. var vertexData = new VertexData();
  30776. vertexData.positions = positions;
  30777. vertexData.indices = indices;
  30778. vertexData.normals = normals;
  30779. vertexData.uvs = uvs;
  30780. if (faceColors && flat) {
  30781. vertexData.colors = colors;
  30782. }
  30783. return vertexData;
  30784. };
  30785. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  30786. /**
  30787. * Creates the VertexData of the Torus Knot.
  30788. */
  30789. VertexData.CreateTorusKnot = function (options) {
  30790. var indices = new Array();
  30791. var positions = new Array();
  30792. var normals = new Array();
  30793. var uvs = new Array();
  30794. var radius = options.radius || 2;
  30795. var tube = options.tube || 0.5;
  30796. var radialSegments = options.radialSegments || 32;
  30797. var tubularSegments = options.tubularSegments || 32;
  30798. var p = options.p || 2;
  30799. var q = options.q || 3;
  30800. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30801. // Helper
  30802. var getPos = function (angle) {
  30803. var cu = Math.cos(angle);
  30804. var su = Math.sin(angle);
  30805. var quOverP = q / p * angle;
  30806. var cs = Math.cos(quOverP);
  30807. var tx = radius * (2 + cs) * 0.5 * cu;
  30808. var ty = radius * (2 + cs) * su * 0.5;
  30809. var tz = radius * Math.sin(quOverP) * 0.5;
  30810. return new BABYLON.Vector3(tx, ty, tz);
  30811. };
  30812. // Vertices
  30813. var i;
  30814. var j;
  30815. for (i = 0; i <= radialSegments; i++) {
  30816. var modI = i % radialSegments;
  30817. var u = modI / radialSegments * 2 * p * Math.PI;
  30818. var p1 = getPos(u);
  30819. var p2 = getPos(u + 0.01);
  30820. var tang = p2.subtract(p1);
  30821. var n = p2.add(p1);
  30822. var bitan = BABYLON.Vector3.Cross(tang, n);
  30823. n = BABYLON.Vector3.Cross(bitan, tang);
  30824. bitan.normalize();
  30825. n.normalize();
  30826. for (j = 0; j < tubularSegments; j++) {
  30827. var modJ = j % tubularSegments;
  30828. var v = modJ / tubularSegments * 2 * Math.PI;
  30829. var cx = -tube * Math.cos(v);
  30830. var cy = tube * Math.sin(v);
  30831. positions.push(p1.x + cx * n.x + cy * bitan.x);
  30832. positions.push(p1.y + cx * n.y + cy * bitan.y);
  30833. positions.push(p1.z + cx * n.z + cy * bitan.z);
  30834. uvs.push(i / radialSegments);
  30835. uvs.push(j / tubularSegments);
  30836. }
  30837. }
  30838. for (i = 0; i < radialSegments; i++) {
  30839. for (j = 0; j < tubularSegments; j++) {
  30840. var jNext = (j + 1) % tubularSegments;
  30841. var a = i * tubularSegments + j;
  30842. var b = (i + 1) * tubularSegments + j;
  30843. var c = (i + 1) * tubularSegments + jNext;
  30844. var d = i * tubularSegments + jNext;
  30845. indices.push(d);
  30846. indices.push(b);
  30847. indices.push(a);
  30848. indices.push(d);
  30849. indices.push(c);
  30850. indices.push(b);
  30851. }
  30852. }
  30853. // Normals
  30854. VertexData.ComputeNormals(positions, indices, normals);
  30855. // Sides
  30856. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30857. // Result
  30858. var vertexData = new VertexData();
  30859. vertexData.indices = indices;
  30860. vertexData.positions = positions;
  30861. vertexData.normals = normals;
  30862. vertexData.uvs = uvs;
  30863. return vertexData;
  30864. };
  30865. // Tools
  30866. /**
  30867. * @param {any} - positions (number[] or Float32Array)
  30868. * @param {any} - indices (number[] or Uint16Array)
  30869. * @param {any} - normals (number[] or Float32Array)
  30870. * options (optional) :
  30871. * facetPositions : optional array of facet positions (vector3)
  30872. * facetNormals : optional array of facet normals (vector3)
  30873. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  30874. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  30875. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  30876. * bbSize : optional bounding box size data, required for facetPartitioning computation
  30877. * bInfo : optional bounding info, required for facetPartitioning computation
  30878. * useRightHandedSystem: optional boolean to for right handed system computation
  30879. * depthSort : optional boolean to enable the facet depth sort computation
  30880. * distanceTo : optional Vector3 to compute the facet depth from this location
  30881. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  30882. */
  30883. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  30884. // temporary scalar variables
  30885. var index = 0; // facet index
  30886. var p1p2x = 0.0; // p1p2 vector x coordinate
  30887. var p1p2y = 0.0; // p1p2 vector y coordinate
  30888. var p1p2z = 0.0; // p1p2 vector z coordinate
  30889. var p3p2x = 0.0; // p3p2 vector x coordinate
  30890. var p3p2y = 0.0; // p3p2 vector y coordinate
  30891. var p3p2z = 0.0; // p3p2 vector z coordinate
  30892. var faceNormalx = 0.0; // facet normal x coordinate
  30893. var faceNormaly = 0.0; // facet normal y coordinate
  30894. var faceNormalz = 0.0; // facet normal z coordinate
  30895. var length = 0.0; // facet normal length before normalization
  30896. var v1x = 0; // vector1 x index in the positions array
  30897. var v1y = 0; // vector1 y index in the positions array
  30898. var v1z = 0; // vector1 z index in the positions array
  30899. var v2x = 0; // vector2 x index in the positions array
  30900. var v2y = 0; // vector2 y index in the positions array
  30901. var v2z = 0; // vector2 z index in the positions array
  30902. var v3x = 0; // vector3 x index in the positions array
  30903. var v3y = 0; // vector3 y index in the positions array
  30904. var v3z = 0; // vector3 z index in the positions array
  30905. var computeFacetNormals = false;
  30906. var computeFacetPositions = false;
  30907. var computeFacetPartitioning = false;
  30908. var computeDepthSort = false;
  30909. var faceNormalSign = 1;
  30910. var ratio = 0;
  30911. var distanceTo = null;
  30912. if (options) {
  30913. computeFacetNormals = (options.facetNormals) ? true : false;
  30914. computeFacetPositions = (options.facetPositions) ? true : false;
  30915. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  30916. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  30917. ratio = options.ratio || 0;
  30918. computeDepthSort = (options.depthSort) ? true : false;
  30919. distanceTo = (options.distanceTo);
  30920. if (computeDepthSort) {
  30921. if (distanceTo === undefined) {
  30922. distanceTo = BABYLON.Vector3.Zero();
  30923. }
  30924. var depthSortedFacets = options.depthSortedFacets;
  30925. }
  30926. }
  30927. // facetPartitioning reinit if needed
  30928. var xSubRatio = 0;
  30929. var ySubRatio = 0;
  30930. var zSubRatio = 0;
  30931. var subSq = 0;
  30932. if (computeFacetPartitioning && options && options.bbSize) {
  30933. var ox = 0; // X partitioning index for facet position
  30934. var oy = 0; // Y partinioning index for facet position
  30935. var oz = 0; // Z partinioning index for facet position
  30936. var b1x = 0; // X partitioning index for facet v1 vertex
  30937. var b1y = 0; // Y partitioning index for facet v1 vertex
  30938. var b1z = 0; // z partitioning index for facet v1 vertex
  30939. var b2x = 0; // X partitioning index for facet v2 vertex
  30940. var b2y = 0; // Y partitioning index for facet v2 vertex
  30941. var b2z = 0; // Z partitioning index for facet v2 vertex
  30942. var b3x = 0; // X partitioning index for facet v3 vertex
  30943. var b3y = 0; // Y partitioning index for facet v3 vertex
  30944. var b3z = 0; // Z partitioning index for facet v3 vertex
  30945. var block_idx_o = 0; // facet barycenter block index
  30946. var block_idx_v1 = 0; // v1 vertex block index
  30947. var block_idx_v2 = 0; // v2 vertex block index
  30948. var block_idx_v3 = 0; // v3 vertex block index
  30949. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  30950. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  30951. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  30952. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  30953. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  30954. subSq = options.subDiv.max * options.subDiv.max;
  30955. options.facetPartitioning.length = 0;
  30956. }
  30957. // reset the normals
  30958. for (index = 0; index < positions.length; index++) {
  30959. normals[index] = 0.0;
  30960. }
  30961. // Loop : 1 indice triplet = 1 facet
  30962. var nbFaces = (indices.length / 3) | 0;
  30963. for (index = 0; index < nbFaces; index++) {
  30964. // get the indexes of the coordinates of each vertex of the facet
  30965. v1x = indices[index * 3] * 3;
  30966. v1y = v1x + 1;
  30967. v1z = v1x + 2;
  30968. v2x = indices[index * 3 + 1] * 3;
  30969. v2y = v2x + 1;
  30970. v2z = v2x + 2;
  30971. v3x = indices[index * 3 + 2] * 3;
  30972. v3y = v3x + 1;
  30973. v3z = v3x + 2;
  30974. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  30975. p1p2y = positions[v1y] - positions[v2y];
  30976. p1p2z = positions[v1z] - positions[v2z];
  30977. p3p2x = positions[v3x] - positions[v2x];
  30978. p3p2y = positions[v3y] - positions[v2y];
  30979. p3p2z = positions[v3z] - positions[v2z];
  30980. // compute the face normal with the cross product
  30981. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  30982. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  30983. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  30984. // normalize this normal and store it in the array facetData
  30985. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30986. length = (length === 0) ? 1.0 : length;
  30987. faceNormalx /= length;
  30988. faceNormaly /= length;
  30989. faceNormalz /= length;
  30990. if (computeFacetNormals && options) {
  30991. options.facetNormals[index].x = faceNormalx;
  30992. options.facetNormals[index].y = faceNormaly;
  30993. options.facetNormals[index].z = faceNormalz;
  30994. }
  30995. if (computeFacetPositions && options) {
  30996. // compute and the facet barycenter coordinates in the array facetPositions
  30997. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  30998. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  30999. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  31000. }
  31001. if (computeFacetPartitioning && options) {
  31002. // store the facet indexes in arrays in the main facetPartitioning array :
  31003. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  31004. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  31005. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  31006. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  31007. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31008. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31009. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31010. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31011. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31012. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31013. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31014. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31015. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31016. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  31017. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  31018. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  31019. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  31020. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  31021. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  31022. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  31023. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  31024. // push each facet index in each block containing the vertex
  31025. options.facetPartitioning[block_idx_v1].push(index);
  31026. if (block_idx_v2 != block_idx_v1) {
  31027. options.facetPartitioning[block_idx_v2].push(index);
  31028. }
  31029. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  31030. options.facetPartitioning[block_idx_v3].push(index);
  31031. }
  31032. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  31033. options.facetPartitioning[block_idx_o].push(index);
  31034. }
  31035. }
  31036. if (computeDepthSort && options && options.facetPositions) {
  31037. var dsf = depthSortedFacets[index];
  31038. dsf.ind = index * 3;
  31039. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  31040. }
  31041. // compute the normals anyway
  31042. normals[v1x] += faceNormalx; // accumulate all the normals per face
  31043. normals[v1y] += faceNormaly;
  31044. normals[v1z] += faceNormalz;
  31045. normals[v2x] += faceNormalx;
  31046. normals[v2y] += faceNormaly;
  31047. normals[v2z] += faceNormalz;
  31048. normals[v3x] += faceNormalx;
  31049. normals[v3y] += faceNormaly;
  31050. normals[v3z] += faceNormalz;
  31051. }
  31052. // last normalization of each normal
  31053. for (index = 0; index < normals.length / 3; index++) {
  31054. faceNormalx = normals[index * 3];
  31055. faceNormaly = normals[index * 3 + 1];
  31056. faceNormalz = normals[index * 3 + 2];
  31057. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31058. length = (length === 0) ? 1.0 : length;
  31059. faceNormalx /= length;
  31060. faceNormaly /= length;
  31061. faceNormalz /= length;
  31062. normals[index * 3] = faceNormalx;
  31063. normals[index * 3 + 1] = faceNormaly;
  31064. normals[index * 3 + 2] = faceNormalz;
  31065. }
  31066. };
  31067. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  31068. var li = indices.length;
  31069. var ln = normals.length;
  31070. var i;
  31071. var n;
  31072. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31073. switch (sideOrientation) {
  31074. case BABYLON.Mesh.FRONTSIDE:
  31075. // nothing changed
  31076. break;
  31077. case BABYLON.Mesh.BACKSIDE:
  31078. var tmp;
  31079. // indices
  31080. for (i = 0; i < li; i += 3) {
  31081. tmp = indices[i];
  31082. indices[i] = indices[i + 2];
  31083. indices[i + 2] = tmp;
  31084. }
  31085. // normals
  31086. for (n = 0; n < ln; n++) {
  31087. normals[n] = -normals[n];
  31088. }
  31089. break;
  31090. case BABYLON.Mesh.DOUBLESIDE:
  31091. // positions
  31092. var lp = positions.length;
  31093. var l = lp / 3;
  31094. for (var p = 0; p < lp; p++) {
  31095. positions[lp + p] = positions[p];
  31096. }
  31097. // indices
  31098. for (i = 0; i < li; i += 3) {
  31099. indices[i + li] = indices[i + 2] + l;
  31100. indices[i + 1 + li] = indices[i + 1] + l;
  31101. indices[i + 2 + li] = indices[i] + l;
  31102. }
  31103. // normals
  31104. for (n = 0; n < ln; n++) {
  31105. normals[ln + n] = -normals[n];
  31106. }
  31107. // uvs
  31108. var lu = uvs.length;
  31109. var u = 0;
  31110. for (u = 0; u < lu; u++) {
  31111. uvs[u + lu] = uvs[u];
  31112. }
  31113. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  31114. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  31115. u = 0;
  31116. for (i = 0; i < lu / 2; i++) {
  31117. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  31118. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  31119. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  31120. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  31121. u += 2;
  31122. }
  31123. break;
  31124. }
  31125. };
  31126. /**
  31127. * Creates a new VertexData from the imported parameters.
  31128. */
  31129. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  31130. var vertexData = new VertexData();
  31131. // positions
  31132. var positions = parsedVertexData.positions;
  31133. if (positions) {
  31134. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  31135. }
  31136. // normals
  31137. var normals = parsedVertexData.normals;
  31138. if (normals) {
  31139. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  31140. }
  31141. // tangents
  31142. var tangents = parsedVertexData.tangents;
  31143. if (tangents) {
  31144. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  31145. }
  31146. // uvs
  31147. var uvs = parsedVertexData.uvs;
  31148. if (uvs) {
  31149. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  31150. }
  31151. // uv2s
  31152. var uv2s = parsedVertexData.uv2s;
  31153. if (uv2s) {
  31154. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  31155. }
  31156. // uv3s
  31157. var uv3s = parsedVertexData.uv3s;
  31158. if (uv3s) {
  31159. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  31160. }
  31161. // uv4s
  31162. var uv4s = parsedVertexData.uv4s;
  31163. if (uv4s) {
  31164. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  31165. }
  31166. // uv5s
  31167. var uv5s = parsedVertexData.uv5s;
  31168. if (uv5s) {
  31169. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  31170. }
  31171. // uv6s
  31172. var uv6s = parsedVertexData.uv6s;
  31173. if (uv6s) {
  31174. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  31175. }
  31176. // colors
  31177. var colors = parsedVertexData.colors;
  31178. if (colors) {
  31179. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  31180. }
  31181. // matricesIndices
  31182. var matricesIndices = parsedVertexData.matricesIndices;
  31183. if (matricesIndices) {
  31184. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  31185. }
  31186. // matricesWeights
  31187. var matricesWeights = parsedVertexData.matricesWeights;
  31188. if (matricesWeights) {
  31189. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  31190. }
  31191. // indices
  31192. var indices = parsedVertexData.indices;
  31193. if (indices) {
  31194. vertexData.indices = indices;
  31195. }
  31196. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  31197. };
  31198. return VertexData;
  31199. }());
  31200. BABYLON.VertexData = VertexData;
  31201. })(BABYLON || (BABYLON = {}));
  31202. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  31203. var BABYLON;
  31204. (function (BABYLON) {
  31205. var Geometry = /** @class */ (function () {
  31206. function Geometry(id, scene, vertexData, updatable, mesh) {
  31207. if (updatable === void 0) { updatable = false; }
  31208. if (mesh === void 0) { mesh = null; }
  31209. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31210. this._totalVertices = 0;
  31211. this._isDisposed = false;
  31212. this._indexBufferIsUpdatable = false;
  31213. this.id = id;
  31214. this._engine = scene.getEngine();
  31215. this._meshes = [];
  31216. this._scene = scene;
  31217. //Init vertex buffer cache
  31218. this._vertexBuffers = {};
  31219. this._indices = [];
  31220. this._updatable = updatable;
  31221. // vertexData
  31222. if (vertexData) {
  31223. this.setAllVerticesData(vertexData, updatable);
  31224. }
  31225. else {
  31226. this._totalVertices = 0;
  31227. this._indices = [];
  31228. }
  31229. if (this._engine.getCaps().vertexArrayObject) {
  31230. this._vertexArrayObjects = {};
  31231. }
  31232. // applyToMesh
  31233. if (mesh) {
  31234. if (mesh.getClassName() === "LinesMesh") {
  31235. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  31236. this.updateExtend();
  31237. }
  31238. this.applyToMesh(mesh);
  31239. mesh.computeWorldMatrix(true);
  31240. }
  31241. }
  31242. Object.defineProperty(Geometry.prototype, "boundingBias", {
  31243. /**
  31244. * 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
  31245. * @returns The Bias Vector
  31246. */
  31247. get: function () {
  31248. return this._boundingBias;
  31249. },
  31250. set: function (value) {
  31251. if (this._boundingBias && this._boundingBias.equals(value)) {
  31252. return;
  31253. }
  31254. this._boundingBias = value.clone();
  31255. this.updateBoundingInfo(true, null);
  31256. },
  31257. enumerable: true,
  31258. configurable: true
  31259. });
  31260. Geometry.CreateGeometryForMesh = function (mesh) {
  31261. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  31262. geometry.applyToMesh(mesh);
  31263. return geometry;
  31264. };
  31265. Object.defineProperty(Geometry.prototype, "extend", {
  31266. get: function () {
  31267. return this._extend;
  31268. },
  31269. enumerable: true,
  31270. configurable: true
  31271. });
  31272. Geometry.prototype.getScene = function () {
  31273. return this._scene;
  31274. };
  31275. Geometry.prototype.getEngine = function () {
  31276. return this._engine;
  31277. };
  31278. Geometry.prototype.isReady = function () {
  31279. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  31280. };
  31281. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  31282. get: function () {
  31283. for (var index = 0; index < this._meshes.length; index++) {
  31284. if (!this._meshes[index].doNotSerialize) {
  31285. return false;
  31286. }
  31287. }
  31288. return true;
  31289. },
  31290. enumerable: true,
  31291. configurable: true
  31292. });
  31293. Geometry.prototype._rebuild = function () {
  31294. if (this._vertexArrayObjects) {
  31295. this._vertexArrayObjects = {};
  31296. }
  31297. // Index buffer
  31298. if (this._meshes.length !== 0 && this._indices) {
  31299. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31300. }
  31301. // Vertex buffers
  31302. for (var key in this._vertexBuffers) {
  31303. var vertexBuffer = this._vertexBuffers[key];
  31304. vertexBuffer._rebuild();
  31305. }
  31306. };
  31307. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  31308. vertexData.applyToGeometry(this, updatable);
  31309. this.notifyUpdate();
  31310. };
  31311. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31312. if (updatable === void 0) { updatable = false; }
  31313. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  31314. this.setVerticesBuffer(buffer);
  31315. };
  31316. Geometry.prototype.removeVerticesData = function (kind) {
  31317. if (this._vertexBuffers[kind]) {
  31318. this._vertexBuffers[kind].dispose();
  31319. delete this._vertexBuffers[kind];
  31320. }
  31321. };
  31322. Geometry.prototype.setVerticesBuffer = function (buffer) {
  31323. var kind = buffer.getKind();
  31324. if (this._vertexBuffers[kind]) {
  31325. this._vertexBuffers[kind].dispose();
  31326. }
  31327. this._vertexBuffers[kind] = buffer;
  31328. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31329. var data = buffer.getData();
  31330. var stride = buffer.getStrideSize();
  31331. this._totalVertices = data.length / stride;
  31332. this.updateExtend(data, stride);
  31333. this._resetPointsArrayCache();
  31334. var meshes = this._meshes;
  31335. var numOfMeshes = meshes.length;
  31336. for (var index = 0; index < numOfMeshes; index++) {
  31337. var mesh = meshes[index];
  31338. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31339. mesh._createGlobalSubMesh(false);
  31340. mesh.computeWorldMatrix(true);
  31341. }
  31342. }
  31343. this.notifyUpdate(kind);
  31344. if (this._vertexArrayObjects) {
  31345. this._disposeVertexArrayObjects();
  31346. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  31347. }
  31348. };
  31349. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  31350. var vertexBuffer = this.getVertexBuffer(kind);
  31351. if (!vertexBuffer) {
  31352. return;
  31353. }
  31354. vertexBuffer.updateDirectly(data, offset);
  31355. this.notifyUpdate(kind);
  31356. };
  31357. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  31358. if (updateExtends === void 0) { updateExtends = false; }
  31359. var vertexBuffer = this.getVertexBuffer(kind);
  31360. if (!vertexBuffer) {
  31361. return;
  31362. }
  31363. vertexBuffer.update(data);
  31364. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31365. var stride = vertexBuffer.getStrideSize();
  31366. this._totalVertices = data.length / stride;
  31367. this.updateBoundingInfo(updateExtends, data);
  31368. }
  31369. this.notifyUpdate(kind);
  31370. };
  31371. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  31372. if (updateExtends) {
  31373. this.updateExtend(data);
  31374. }
  31375. var meshes = this._meshes;
  31376. var numOfMeshes = meshes.length;
  31377. this._resetPointsArrayCache();
  31378. for (var index = 0; index < numOfMeshes; index++) {
  31379. var mesh = meshes[index];
  31380. if (updateExtends) {
  31381. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31382. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  31383. var subMesh = mesh.subMeshes[subIndex];
  31384. subMesh.refreshBoundingInfo();
  31385. }
  31386. }
  31387. }
  31388. };
  31389. Geometry.prototype._bind = function (effect, indexToBind) {
  31390. if (!effect) {
  31391. return;
  31392. }
  31393. if (indexToBind === undefined) {
  31394. indexToBind = this._indexBuffer;
  31395. }
  31396. var vbs = this.getVertexBuffers();
  31397. if (!vbs) {
  31398. return;
  31399. }
  31400. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  31401. this._engine.bindBuffers(vbs, indexToBind, effect);
  31402. return;
  31403. }
  31404. // Using VAO
  31405. if (!this._vertexArrayObjects[effect.key]) {
  31406. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  31407. }
  31408. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  31409. };
  31410. Geometry.prototype.getTotalVertices = function () {
  31411. if (!this.isReady()) {
  31412. return 0;
  31413. }
  31414. return this._totalVertices;
  31415. };
  31416. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31417. var vertexBuffer = this.getVertexBuffer(kind);
  31418. if (!vertexBuffer) {
  31419. return null;
  31420. }
  31421. var orig = vertexBuffer.getData();
  31422. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  31423. return orig;
  31424. }
  31425. else {
  31426. var len = orig.length;
  31427. var copy = [];
  31428. for (var i = 0; i < len; i++) {
  31429. copy.push(orig[i]);
  31430. }
  31431. return copy;
  31432. }
  31433. };
  31434. /**
  31435. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31436. * Possible `kind` values :
  31437. * - BABYLON.VertexBuffer.PositionKind
  31438. * - BABYLON.VertexBuffer.UVKind
  31439. * - BABYLON.VertexBuffer.UV2Kind
  31440. * - BABYLON.VertexBuffer.UV3Kind
  31441. * - BABYLON.VertexBuffer.UV4Kind
  31442. * - BABYLON.VertexBuffer.UV5Kind
  31443. * - BABYLON.VertexBuffer.UV6Kind
  31444. * - BABYLON.VertexBuffer.ColorKind
  31445. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31446. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31447. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31448. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31449. */
  31450. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  31451. var vb = this._vertexBuffers[kind];
  31452. if (!vb) {
  31453. return false;
  31454. }
  31455. return vb.isUpdatable();
  31456. };
  31457. Geometry.prototype.getVertexBuffer = function (kind) {
  31458. if (!this.isReady()) {
  31459. return null;
  31460. }
  31461. return this._vertexBuffers[kind];
  31462. };
  31463. Geometry.prototype.getVertexBuffers = function () {
  31464. if (!this.isReady()) {
  31465. return null;
  31466. }
  31467. return this._vertexBuffers;
  31468. };
  31469. Geometry.prototype.isVerticesDataPresent = function (kind) {
  31470. if (!this._vertexBuffers) {
  31471. if (this._delayInfo) {
  31472. return this._delayInfo.indexOf(kind) !== -1;
  31473. }
  31474. return false;
  31475. }
  31476. return this._vertexBuffers[kind] !== undefined;
  31477. };
  31478. Geometry.prototype.getVerticesDataKinds = function () {
  31479. var result = [];
  31480. var kind;
  31481. if (!this._vertexBuffers && this._delayInfo) {
  31482. for (kind in this._delayInfo) {
  31483. result.push(kind);
  31484. }
  31485. }
  31486. else {
  31487. for (kind in this._vertexBuffers) {
  31488. result.push(kind);
  31489. }
  31490. }
  31491. return result;
  31492. };
  31493. Geometry.prototype.updateIndices = function (indices, offset) {
  31494. if (!this._indexBuffer) {
  31495. return;
  31496. }
  31497. if (!this._indexBufferIsUpdatable) {
  31498. this.setIndices(indices, null, true);
  31499. }
  31500. else {
  31501. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  31502. }
  31503. };
  31504. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  31505. if (totalVertices === void 0) { totalVertices = null; }
  31506. if (updatable === void 0) { updatable = false; }
  31507. if (this._indexBuffer) {
  31508. this._engine._releaseBuffer(this._indexBuffer);
  31509. }
  31510. this._disposeVertexArrayObjects();
  31511. this._indices = indices;
  31512. this._indexBufferIsUpdatable = updatable;
  31513. if (this._meshes.length !== 0 && this._indices) {
  31514. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  31515. }
  31516. if (totalVertices != undefined) {
  31517. this._totalVertices = totalVertices;
  31518. }
  31519. var meshes = this._meshes;
  31520. var numOfMeshes = meshes.length;
  31521. for (var index = 0; index < numOfMeshes; index++) {
  31522. meshes[index]._createGlobalSubMesh(true);
  31523. }
  31524. this.notifyUpdate();
  31525. };
  31526. Geometry.prototype.getTotalIndices = function () {
  31527. if (!this.isReady()) {
  31528. return 0;
  31529. }
  31530. return this._indices.length;
  31531. };
  31532. Geometry.prototype.getIndices = function (copyWhenShared) {
  31533. if (!this.isReady()) {
  31534. return null;
  31535. }
  31536. var orig = this._indices;
  31537. if (!copyWhenShared || this._meshes.length === 1) {
  31538. return orig;
  31539. }
  31540. else {
  31541. var len = orig.length;
  31542. var copy = [];
  31543. for (var i = 0; i < len; i++) {
  31544. copy.push(orig[i]);
  31545. }
  31546. return copy;
  31547. }
  31548. };
  31549. Geometry.prototype.getIndexBuffer = function () {
  31550. if (!this.isReady()) {
  31551. return null;
  31552. }
  31553. return this._indexBuffer;
  31554. };
  31555. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  31556. if (effect === void 0) { effect = null; }
  31557. if (!effect || !this._vertexArrayObjects) {
  31558. return;
  31559. }
  31560. if (this._vertexArrayObjects[effect.key]) {
  31561. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  31562. delete this._vertexArrayObjects[effect.key];
  31563. }
  31564. };
  31565. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  31566. var meshes = this._meshes;
  31567. var index = meshes.indexOf(mesh);
  31568. if (index === -1) {
  31569. return;
  31570. }
  31571. meshes.splice(index, 1);
  31572. mesh._geometry = null;
  31573. if (meshes.length === 0 && shouldDispose) {
  31574. this.dispose();
  31575. }
  31576. };
  31577. Geometry.prototype.applyToMesh = function (mesh) {
  31578. if (mesh._geometry === this) {
  31579. return;
  31580. }
  31581. var previousGeometry = mesh._geometry;
  31582. if (previousGeometry) {
  31583. previousGeometry.releaseForMesh(mesh);
  31584. }
  31585. var meshes = this._meshes;
  31586. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  31587. mesh._geometry = this;
  31588. this._scene.pushGeometry(this);
  31589. meshes.push(mesh);
  31590. if (this.isReady()) {
  31591. this._applyToMesh(mesh);
  31592. }
  31593. else {
  31594. mesh._boundingInfo = this._boundingInfo;
  31595. }
  31596. };
  31597. Geometry.prototype.updateExtend = function (data, stride) {
  31598. if (data === void 0) { data = null; }
  31599. if (!data) {
  31600. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  31601. }
  31602. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  31603. };
  31604. Geometry.prototype._applyToMesh = function (mesh) {
  31605. var numOfMeshes = this._meshes.length;
  31606. // vertexBuffers
  31607. for (var kind in this._vertexBuffers) {
  31608. if (numOfMeshes === 1) {
  31609. this._vertexBuffers[kind].create();
  31610. }
  31611. var buffer = this._vertexBuffers[kind].getBuffer();
  31612. if (buffer)
  31613. buffer.references = numOfMeshes;
  31614. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31615. if (!this._extend) {
  31616. this.updateExtend(this._vertexBuffers[kind].getData());
  31617. }
  31618. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31619. mesh._createGlobalSubMesh(false);
  31620. //bounding info was just created again, world matrix should be applied again.
  31621. mesh._updateBoundingInfo();
  31622. }
  31623. }
  31624. // indexBuffer
  31625. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  31626. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31627. }
  31628. if (this._indexBuffer) {
  31629. this._indexBuffer.references = numOfMeshes;
  31630. }
  31631. };
  31632. Geometry.prototype.notifyUpdate = function (kind) {
  31633. if (this.onGeometryUpdated) {
  31634. this.onGeometryUpdated(this, kind);
  31635. }
  31636. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  31637. var mesh = _a[_i];
  31638. mesh._markSubMeshesAsAttributesDirty();
  31639. }
  31640. };
  31641. Geometry.prototype.load = function (scene, onLoaded) {
  31642. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31643. return;
  31644. }
  31645. if (this.isReady()) {
  31646. if (onLoaded) {
  31647. onLoaded();
  31648. }
  31649. return;
  31650. }
  31651. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  31652. this._queueLoad(scene, onLoaded);
  31653. };
  31654. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  31655. var _this = this;
  31656. if (!this.delayLoadingFile) {
  31657. return;
  31658. }
  31659. scene._addPendingData(this);
  31660. scene._loadFile(this.delayLoadingFile, function (data) {
  31661. if (!_this._delayLoadingFunction) {
  31662. return;
  31663. }
  31664. _this._delayLoadingFunction(JSON.parse(data), _this);
  31665. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31666. _this._delayInfo = [];
  31667. scene._removePendingData(_this);
  31668. var meshes = _this._meshes;
  31669. var numOfMeshes = meshes.length;
  31670. for (var index = 0; index < numOfMeshes; index++) {
  31671. _this._applyToMesh(meshes[index]);
  31672. }
  31673. if (onLoaded) {
  31674. onLoaded();
  31675. }
  31676. }, undefined, true);
  31677. };
  31678. /**
  31679. * Invert the geometry to move from a right handed system to a left handed one.
  31680. */
  31681. Geometry.prototype.toLeftHanded = function () {
  31682. // Flip faces
  31683. var tIndices = this.getIndices(false);
  31684. if (tIndices != null && tIndices.length > 0) {
  31685. for (var i = 0; i < tIndices.length; i += 3) {
  31686. var tTemp = tIndices[i + 0];
  31687. tIndices[i + 0] = tIndices[i + 2];
  31688. tIndices[i + 2] = tTemp;
  31689. }
  31690. this.setIndices(tIndices);
  31691. }
  31692. // Negate position.z
  31693. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  31694. if (tPositions != null && tPositions.length > 0) {
  31695. for (var i = 0; i < tPositions.length; i += 3) {
  31696. tPositions[i + 2] = -tPositions[i + 2];
  31697. }
  31698. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  31699. }
  31700. // Negate normal.z
  31701. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  31702. if (tNormals != null && tNormals.length > 0) {
  31703. for (var i = 0; i < tNormals.length; i += 3) {
  31704. tNormals[i + 2] = -tNormals[i + 2];
  31705. }
  31706. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  31707. }
  31708. };
  31709. // Cache
  31710. Geometry.prototype._resetPointsArrayCache = function () {
  31711. this._positions = null;
  31712. };
  31713. Geometry.prototype._generatePointsArray = function () {
  31714. if (this._positions)
  31715. return true;
  31716. this._positions = [];
  31717. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31718. if (!data) {
  31719. return false;
  31720. }
  31721. for (var index = 0; index < data.length; index += 3) {
  31722. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  31723. }
  31724. return true;
  31725. };
  31726. Geometry.prototype.isDisposed = function () {
  31727. return this._isDisposed;
  31728. };
  31729. Geometry.prototype._disposeVertexArrayObjects = function () {
  31730. if (this._vertexArrayObjects) {
  31731. for (var kind in this._vertexArrayObjects) {
  31732. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  31733. }
  31734. this._vertexArrayObjects = {};
  31735. }
  31736. };
  31737. Geometry.prototype.dispose = function () {
  31738. var meshes = this._meshes;
  31739. var numOfMeshes = meshes.length;
  31740. var index;
  31741. for (index = 0; index < numOfMeshes; index++) {
  31742. this.releaseForMesh(meshes[index]);
  31743. }
  31744. this._meshes = [];
  31745. this._disposeVertexArrayObjects();
  31746. for (var kind in this._vertexBuffers) {
  31747. this._vertexBuffers[kind].dispose();
  31748. }
  31749. this._vertexBuffers = {};
  31750. this._totalVertices = 0;
  31751. if (this._indexBuffer) {
  31752. this._engine._releaseBuffer(this._indexBuffer);
  31753. }
  31754. this._indexBuffer = null;
  31755. this._indices = [];
  31756. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31757. this.delayLoadingFile = null;
  31758. this._delayLoadingFunction = null;
  31759. this._delayInfo = [];
  31760. this._boundingInfo = null;
  31761. this._scene.removeGeometry(this);
  31762. this._isDisposed = true;
  31763. };
  31764. Geometry.prototype.copy = function (id) {
  31765. var vertexData = new BABYLON.VertexData();
  31766. vertexData.indices = [];
  31767. var indices = this.getIndices();
  31768. if (indices) {
  31769. for (var index = 0; index < indices.length; index++) {
  31770. vertexData.indices.push(indices[index]);
  31771. }
  31772. }
  31773. var updatable = false;
  31774. var stopChecking = false;
  31775. var kind;
  31776. for (kind in this._vertexBuffers) {
  31777. // using slice() to make a copy of the array and not just reference it
  31778. var data = this.getVerticesData(kind);
  31779. if (data instanceof Float32Array) {
  31780. vertexData.set(new Float32Array(data), kind);
  31781. }
  31782. else {
  31783. vertexData.set(data.slice(0), kind);
  31784. }
  31785. if (!stopChecking) {
  31786. var vb = this.getVertexBuffer(kind);
  31787. if (vb) {
  31788. updatable = vb.isUpdatable();
  31789. stopChecking = !updatable;
  31790. }
  31791. }
  31792. }
  31793. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  31794. geometry.delayLoadState = this.delayLoadState;
  31795. geometry.delayLoadingFile = this.delayLoadingFile;
  31796. geometry._delayLoadingFunction = this._delayLoadingFunction;
  31797. for (kind in this._delayInfo) {
  31798. geometry._delayInfo = geometry._delayInfo || [];
  31799. geometry._delayInfo.push(kind);
  31800. }
  31801. // Bounding info
  31802. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31803. return geometry;
  31804. };
  31805. Geometry.prototype.serialize = function () {
  31806. var serializationObject = {};
  31807. serializationObject.id = this.id;
  31808. serializationObject.updatable = this._updatable;
  31809. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  31810. serializationObject.tags = BABYLON.Tags.GetTags(this);
  31811. }
  31812. return serializationObject;
  31813. };
  31814. Geometry.prototype.toNumberArray = function (origin) {
  31815. if (Array.isArray(origin)) {
  31816. return origin;
  31817. }
  31818. else {
  31819. return Array.prototype.slice.call(origin);
  31820. }
  31821. };
  31822. Geometry.prototype.serializeVerticeData = function () {
  31823. var serializationObject = this.serialize();
  31824. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  31825. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  31826. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  31827. serializationObject.positions._updatable = true;
  31828. }
  31829. }
  31830. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31831. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  31832. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  31833. serializationObject.normals._updatable = true;
  31834. }
  31835. }
  31836. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31837. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  31838. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  31839. serializationObject.uvs._updatable = true;
  31840. }
  31841. }
  31842. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31843. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  31844. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  31845. serializationObject.uv2s._updatable = true;
  31846. }
  31847. }
  31848. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  31849. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  31850. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  31851. serializationObject.uv3s._updatable = true;
  31852. }
  31853. }
  31854. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  31855. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  31856. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  31857. serializationObject.uv4s._updatable = true;
  31858. }
  31859. }
  31860. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  31861. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  31862. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  31863. serializationObject.uv5s._updatable = true;
  31864. }
  31865. }
  31866. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  31867. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  31868. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  31869. serializationObject.uv6s._updatable = true;
  31870. }
  31871. }
  31872. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  31873. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  31874. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  31875. serializationObject.colors._updatable = true;
  31876. }
  31877. }
  31878. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31879. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  31880. serializationObject.matricesIndices._isExpanded = true;
  31881. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31882. serializationObject.matricesIndices._updatable = true;
  31883. }
  31884. }
  31885. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31886. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  31887. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31888. serializationObject.matricesWeights._updatable = true;
  31889. }
  31890. }
  31891. serializationObject.indices = this.toNumberArray(this.getIndices());
  31892. return serializationObject;
  31893. };
  31894. // Statics
  31895. Geometry.ExtractFromMesh = function (mesh, id) {
  31896. var geometry = mesh._geometry;
  31897. if (!geometry) {
  31898. return null;
  31899. }
  31900. return geometry.copy(id);
  31901. };
  31902. /**
  31903. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  31904. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  31905. * Be aware Math.random() could cause collisions, but:
  31906. * "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"
  31907. */
  31908. Geometry.RandomId = function () {
  31909. return BABYLON.Tools.RandomId();
  31910. };
  31911. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  31912. var scene = mesh.getScene();
  31913. // Geometry
  31914. var geometryId = parsedGeometry.geometryId;
  31915. if (geometryId) {
  31916. var geometry = scene.getGeometryByID(geometryId);
  31917. if (geometry) {
  31918. geometry.applyToMesh(mesh);
  31919. }
  31920. }
  31921. else if (parsedGeometry instanceof ArrayBuffer) {
  31922. var binaryInfo = mesh._binaryInfo;
  31923. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  31924. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  31925. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  31926. }
  31927. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  31928. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  31929. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  31930. }
  31931. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  31932. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  31933. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  31934. }
  31935. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  31936. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  31937. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  31938. }
  31939. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  31940. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  31941. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  31942. }
  31943. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  31944. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  31945. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  31946. }
  31947. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  31948. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  31949. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  31950. }
  31951. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  31952. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  31953. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  31954. }
  31955. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  31956. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  31957. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  31958. }
  31959. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  31960. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  31961. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  31962. }
  31963. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  31964. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  31965. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  31966. }
  31967. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  31968. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  31969. mesh.setIndices(indicesData, null);
  31970. }
  31971. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  31972. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  31973. mesh.subMeshes = [];
  31974. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  31975. var materialIndex = subMeshesData[(i * 5) + 0];
  31976. var verticesStart = subMeshesData[(i * 5) + 1];
  31977. var verticesCount = subMeshesData[(i * 5) + 2];
  31978. var indexStart = subMeshesData[(i * 5) + 3];
  31979. var indexCount = subMeshesData[(i * 5) + 4];
  31980. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  31981. }
  31982. }
  31983. }
  31984. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  31985. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  31986. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  31987. if (parsedGeometry.uvs) {
  31988. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  31989. }
  31990. if (parsedGeometry.uvs2) {
  31991. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  31992. }
  31993. if (parsedGeometry.uvs3) {
  31994. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  31995. }
  31996. if (parsedGeometry.uvs4) {
  31997. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  31998. }
  31999. if (parsedGeometry.uvs5) {
  32000. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  32001. }
  32002. if (parsedGeometry.uvs6) {
  32003. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  32004. }
  32005. if (parsedGeometry.colors) {
  32006. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  32007. }
  32008. if (parsedGeometry.matricesIndices) {
  32009. if (!parsedGeometry.matricesIndices._isExpanded) {
  32010. var floatIndices = [];
  32011. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  32012. var matricesIndex = parsedGeometry.matricesIndices[i];
  32013. floatIndices.push(matricesIndex & 0x000000FF);
  32014. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  32015. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  32016. floatIndices.push(matricesIndex >> 24);
  32017. }
  32018. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  32019. }
  32020. else {
  32021. delete parsedGeometry.matricesIndices._isExpanded;
  32022. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  32023. }
  32024. }
  32025. if (parsedGeometry.matricesIndicesExtra) {
  32026. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  32027. var floatIndices = [];
  32028. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  32029. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  32030. floatIndices.push(matricesIndex & 0x000000FF);
  32031. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  32032. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  32033. floatIndices.push(matricesIndex >> 24);
  32034. }
  32035. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  32036. }
  32037. else {
  32038. delete parsedGeometry.matricesIndices._isExpanded;
  32039. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  32040. }
  32041. }
  32042. if (parsedGeometry.matricesWeights) {
  32043. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  32044. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  32045. }
  32046. if (parsedGeometry.matricesWeightsExtra) {
  32047. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  32048. }
  32049. mesh.setIndices(parsedGeometry.indices, null);
  32050. }
  32051. // SubMeshes
  32052. if (parsedGeometry.subMeshes) {
  32053. mesh.subMeshes = [];
  32054. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  32055. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  32056. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  32057. }
  32058. }
  32059. // Flat shading
  32060. if (mesh._shouldGenerateFlatShading) {
  32061. mesh.convertToFlatShadedMesh();
  32062. delete mesh._shouldGenerateFlatShading;
  32063. }
  32064. // Update
  32065. mesh.computeWorldMatrix(true);
  32066. // Octree
  32067. var sceneOctree = scene.selectionOctree;
  32068. if (sceneOctree !== undefined && sceneOctree !== null) {
  32069. sceneOctree.addMesh(mesh);
  32070. }
  32071. };
  32072. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  32073. var epsilon = 1e-3;
  32074. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  32075. return;
  32076. }
  32077. var noInfluenceBoneIndex = 0.0;
  32078. if (parsedGeometry.skeletonId > -1) {
  32079. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  32080. if (!skeleton) {
  32081. return;
  32082. }
  32083. noInfluenceBoneIndex = skeleton.bones.length;
  32084. }
  32085. else {
  32086. return;
  32087. }
  32088. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32089. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32090. var matricesWeights = parsedGeometry.matricesWeights;
  32091. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  32092. var influencers = parsedGeometry.numBoneInfluencer;
  32093. var size = matricesWeights.length;
  32094. for (var i = 0; i < size; i += 4) {
  32095. var weight = 0.0;
  32096. var firstZeroWeight = -1;
  32097. for (var j = 0; j < 4; j++) {
  32098. var w = matricesWeights[i + j];
  32099. weight += w;
  32100. if (w < epsilon && firstZeroWeight < 0) {
  32101. firstZeroWeight = j;
  32102. }
  32103. }
  32104. if (matricesWeightsExtra) {
  32105. for (var j = 0; j < 4; j++) {
  32106. var w = matricesWeightsExtra[i + j];
  32107. weight += w;
  32108. if (w < epsilon && firstZeroWeight < 0) {
  32109. firstZeroWeight = j + 4;
  32110. }
  32111. }
  32112. }
  32113. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32114. firstZeroWeight = influencers - 1;
  32115. }
  32116. if (weight > epsilon) {
  32117. var mweight = 1.0 / weight;
  32118. for (var j = 0; j < 4; j++) {
  32119. matricesWeights[i + j] *= mweight;
  32120. }
  32121. if (matricesWeightsExtra) {
  32122. for (var j = 0; j < 4; j++) {
  32123. matricesWeightsExtra[i + j] *= mweight;
  32124. }
  32125. }
  32126. }
  32127. else {
  32128. if (firstZeroWeight >= 4) {
  32129. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32130. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32131. }
  32132. else {
  32133. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32134. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32135. }
  32136. }
  32137. }
  32138. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32139. if (parsedGeometry.matricesWeightsExtra) {
  32140. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32141. }
  32142. };
  32143. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  32144. if (scene.getGeometryByID(parsedVertexData.id)) {
  32145. return null; // null since geometry could be something else than a box...
  32146. }
  32147. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  32148. if (BABYLON.Tags) {
  32149. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  32150. }
  32151. if (parsedVertexData.delayLoadingFile) {
  32152. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32153. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  32154. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  32155. geometry._delayInfo = [];
  32156. if (parsedVertexData.hasUVs) {
  32157. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32158. }
  32159. if (parsedVertexData.hasUVs2) {
  32160. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32161. }
  32162. if (parsedVertexData.hasUVs3) {
  32163. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32164. }
  32165. if (parsedVertexData.hasUVs4) {
  32166. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32167. }
  32168. if (parsedVertexData.hasUVs5) {
  32169. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  32170. }
  32171. if (parsedVertexData.hasUVs6) {
  32172. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  32173. }
  32174. if (parsedVertexData.hasColors) {
  32175. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  32176. }
  32177. if (parsedVertexData.hasMatricesIndices) {
  32178. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32179. }
  32180. if (parsedVertexData.hasMatricesWeights) {
  32181. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32182. }
  32183. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  32184. }
  32185. else {
  32186. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  32187. }
  32188. scene.pushGeometry(geometry, true);
  32189. return geometry;
  32190. };
  32191. return Geometry;
  32192. }());
  32193. BABYLON.Geometry = Geometry;
  32194. /////// Primitives //////////////////////////////////////////////
  32195. (function (Geometry) {
  32196. var Primitives;
  32197. (function (Primitives) {
  32198. /// Abstract class
  32199. var _Primitive = /** @class */ (function (_super) {
  32200. __extends(_Primitive, _super);
  32201. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  32202. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  32203. if (mesh === void 0) { mesh = null; }
  32204. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  32205. _this._canBeRegenerated = _canBeRegenerated;
  32206. _this._beingRegenerated = true;
  32207. _this.regenerate();
  32208. _this._beingRegenerated = false;
  32209. return _this;
  32210. }
  32211. _Primitive.prototype.canBeRegenerated = function () {
  32212. return this._canBeRegenerated;
  32213. };
  32214. _Primitive.prototype.regenerate = function () {
  32215. if (!this._canBeRegenerated) {
  32216. return;
  32217. }
  32218. this._beingRegenerated = true;
  32219. this.setAllVerticesData(this._regenerateVertexData(), false);
  32220. this._beingRegenerated = false;
  32221. };
  32222. _Primitive.prototype.asNewGeometry = function (id) {
  32223. return _super.prototype.copy.call(this, id);
  32224. };
  32225. // overrides
  32226. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  32227. if (!this._beingRegenerated) {
  32228. return;
  32229. }
  32230. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  32231. };
  32232. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  32233. if (!this._beingRegenerated) {
  32234. return;
  32235. }
  32236. _super.prototype.setVerticesData.call(this, kind, data, false);
  32237. };
  32238. // to override
  32239. // protected
  32240. _Primitive.prototype._regenerateVertexData = function () {
  32241. throw new Error("Abstract method");
  32242. };
  32243. _Primitive.prototype.copy = function (id) {
  32244. throw new Error("Must be overriden in sub-classes.");
  32245. };
  32246. _Primitive.prototype.serialize = function () {
  32247. var serializationObject = _super.prototype.serialize.call(this);
  32248. serializationObject.canBeRegenerated = this.canBeRegenerated();
  32249. return serializationObject;
  32250. };
  32251. return _Primitive;
  32252. }(Geometry));
  32253. Primitives._Primitive = _Primitive;
  32254. var Ribbon = /** @class */ (function (_super) {
  32255. __extends(Ribbon, _super);
  32256. // Members
  32257. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  32258. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32259. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32260. _this.pathArray = pathArray;
  32261. _this.closeArray = closeArray;
  32262. _this.closePath = closePath;
  32263. _this.offset = offset;
  32264. _this.side = side;
  32265. return _this;
  32266. }
  32267. Ribbon.prototype._regenerateVertexData = function () {
  32268. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  32269. };
  32270. Ribbon.prototype.copy = function (id) {
  32271. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  32272. };
  32273. return Ribbon;
  32274. }(_Primitive));
  32275. Primitives.Ribbon = Ribbon;
  32276. var Box = /** @class */ (function (_super) {
  32277. __extends(Box, _super);
  32278. // Members
  32279. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  32280. if (mesh === void 0) { mesh = null; }
  32281. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32282. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32283. _this.size = size;
  32284. _this.side = side;
  32285. return _this;
  32286. }
  32287. Box.prototype._regenerateVertexData = function () {
  32288. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  32289. };
  32290. Box.prototype.copy = function (id) {
  32291. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  32292. };
  32293. Box.prototype.serialize = function () {
  32294. var serializationObject = _super.prototype.serialize.call(this);
  32295. serializationObject.size = this.size;
  32296. return serializationObject;
  32297. };
  32298. Box.Parse = function (parsedBox, scene) {
  32299. if (scene.getGeometryByID(parsedBox.id)) {
  32300. return null; // null since geometry could be something else than a box...
  32301. }
  32302. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  32303. if (BABYLON.Tags) {
  32304. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  32305. }
  32306. scene.pushGeometry(box, true);
  32307. return box;
  32308. };
  32309. return Box;
  32310. }(_Primitive));
  32311. Primitives.Box = Box;
  32312. var Sphere = /** @class */ (function (_super) {
  32313. __extends(Sphere, _super);
  32314. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  32315. if (mesh === void 0) { mesh = null; }
  32316. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32317. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32318. _this.segments = segments;
  32319. _this.diameter = diameter;
  32320. _this.side = side;
  32321. return _this;
  32322. }
  32323. Sphere.prototype._regenerateVertexData = function () {
  32324. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  32325. };
  32326. Sphere.prototype.copy = function (id) {
  32327. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  32328. };
  32329. Sphere.prototype.serialize = function () {
  32330. var serializationObject = _super.prototype.serialize.call(this);
  32331. serializationObject.segments = this.segments;
  32332. serializationObject.diameter = this.diameter;
  32333. return serializationObject;
  32334. };
  32335. Sphere.Parse = function (parsedSphere, scene) {
  32336. if (scene.getGeometryByID(parsedSphere.id)) {
  32337. return null; // null since geometry could be something else than a sphere...
  32338. }
  32339. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  32340. if (BABYLON.Tags) {
  32341. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  32342. }
  32343. scene.pushGeometry(sphere, true);
  32344. return sphere;
  32345. };
  32346. return Sphere;
  32347. }(_Primitive));
  32348. Primitives.Sphere = Sphere;
  32349. var Disc = /** @class */ (function (_super) {
  32350. __extends(Disc, _super);
  32351. // Members
  32352. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  32353. if (mesh === void 0) { mesh = null; }
  32354. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32355. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32356. _this.radius = radius;
  32357. _this.tessellation = tessellation;
  32358. _this.side = side;
  32359. return _this;
  32360. }
  32361. Disc.prototype._regenerateVertexData = function () {
  32362. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  32363. };
  32364. Disc.prototype.copy = function (id) {
  32365. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  32366. };
  32367. return Disc;
  32368. }(_Primitive));
  32369. Primitives.Disc = Disc;
  32370. var Cylinder = /** @class */ (function (_super) {
  32371. __extends(Cylinder, _super);
  32372. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  32373. if (subdivisions === void 0) { subdivisions = 1; }
  32374. if (mesh === void 0) { mesh = null; }
  32375. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32376. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32377. _this.height = height;
  32378. _this.diameterTop = diameterTop;
  32379. _this.diameterBottom = diameterBottom;
  32380. _this.tessellation = tessellation;
  32381. _this.subdivisions = subdivisions;
  32382. _this.side = side;
  32383. return _this;
  32384. }
  32385. Cylinder.prototype._regenerateVertexData = function () {
  32386. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  32387. };
  32388. Cylinder.prototype.copy = function (id) {
  32389. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  32390. };
  32391. Cylinder.prototype.serialize = function () {
  32392. var serializationObject = _super.prototype.serialize.call(this);
  32393. serializationObject.height = this.height;
  32394. serializationObject.diameterTop = this.diameterTop;
  32395. serializationObject.diameterBottom = this.diameterBottom;
  32396. serializationObject.tessellation = this.tessellation;
  32397. return serializationObject;
  32398. };
  32399. Cylinder.Parse = function (parsedCylinder, scene) {
  32400. if (scene.getGeometryByID(parsedCylinder.id)) {
  32401. return null; // null since geometry could be something else than a cylinder...
  32402. }
  32403. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  32404. if (BABYLON.Tags) {
  32405. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  32406. }
  32407. scene.pushGeometry(cylinder, true);
  32408. return cylinder;
  32409. };
  32410. return Cylinder;
  32411. }(_Primitive));
  32412. Primitives.Cylinder = Cylinder;
  32413. var Torus = /** @class */ (function (_super) {
  32414. __extends(Torus, _super);
  32415. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  32416. if (mesh === void 0) { mesh = null; }
  32417. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32418. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32419. _this.diameter = diameter;
  32420. _this.thickness = thickness;
  32421. _this.tessellation = tessellation;
  32422. _this.side = side;
  32423. return _this;
  32424. }
  32425. Torus.prototype._regenerateVertexData = function () {
  32426. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  32427. };
  32428. Torus.prototype.copy = function (id) {
  32429. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  32430. };
  32431. Torus.prototype.serialize = function () {
  32432. var serializationObject = _super.prototype.serialize.call(this);
  32433. serializationObject.diameter = this.diameter;
  32434. serializationObject.thickness = this.thickness;
  32435. serializationObject.tessellation = this.tessellation;
  32436. return serializationObject;
  32437. };
  32438. Torus.Parse = function (parsedTorus, scene) {
  32439. if (scene.getGeometryByID(parsedTorus.id)) {
  32440. return null; // null since geometry could be something else than a torus...
  32441. }
  32442. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  32443. if (BABYLON.Tags) {
  32444. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  32445. }
  32446. scene.pushGeometry(torus, true);
  32447. return torus;
  32448. };
  32449. return Torus;
  32450. }(_Primitive));
  32451. Primitives.Torus = Torus;
  32452. var Ground = /** @class */ (function (_super) {
  32453. __extends(Ground, _super);
  32454. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  32455. if (mesh === void 0) { mesh = null; }
  32456. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32457. _this.width = width;
  32458. _this.height = height;
  32459. _this.subdivisions = subdivisions;
  32460. return _this;
  32461. }
  32462. Ground.prototype._regenerateVertexData = function () {
  32463. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  32464. };
  32465. Ground.prototype.copy = function (id) {
  32466. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  32467. };
  32468. Ground.prototype.serialize = function () {
  32469. var serializationObject = _super.prototype.serialize.call(this);
  32470. serializationObject.width = this.width;
  32471. serializationObject.height = this.height;
  32472. serializationObject.subdivisions = this.subdivisions;
  32473. return serializationObject;
  32474. };
  32475. Ground.Parse = function (parsedGround, scene) {
  32476. if (scene.getGeometryByID(parsedGround.id)) {
  32477. return null; // null since geometry could be something else than a ground...
  32478. }
  32479. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  32480. if (BABYLON.Tags) {
  32481. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  32482. }
  32483. scene.pushGeometry(ground, true);
  32484. return ground;
  32485. };
  32486. return Ground;
  32487. }(_Primitive));
  32488. Primitives.Ground = Ground;
  32489. var TiledGround = /** @class */ (function (_super) {
  32490. __extends(TiledGround, _super);
  32491. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  32492. if (mesh === void 0) { mesh = null; }
  32493. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32494. _this.xmin = xmin;
  32495. _this.zmin = zmin;
  32496. _this.xmax = xmax;
  32497. _this.zmax = zmax;
  32498. _this.subdivisions = subdivisions;
  32499. _this.precision = precision;
  32500. return _this;
  32501. }
  32502. TiledGround.prototype._regenerateVertexData = function () {
  32503. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  32504. };
  32505. TiledGround.prototype.copy = function (id) {
  32506. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  32507. };
  32508. return TiledGround;
  32509. }(_Primitive));
  32510. Primitives.TiledGround = TiledGround;
  32511. var Plane = /** @class */ (function (_super) {
  32512. __extends(Plane, _super);
  32513. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  32514. if (mesh === void 0) { mesh = null; }
  32515. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32516. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32517. _this.size = size;
  32518. _this.side = side;
  32519. return _this;
  32520. }
  32521. Plane.prototype._regenerateVertexData = function () {
  32522. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  32523. };
  32524. Plane.prototype.copy = function (id) {
  32525. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  32526. };
  32527. Plane.prototype.serialize = function () {
  32528. var serializationObject = _super.prototype.serialize.call(this);
  32529. serializationObject.size = this.size;
  32530. return serializationObject;
  32531. };
  32532. Plane.Parse = function (parsedPlane, scene) {
  32533. if (scene.getGeometryByID(parsedPlane.id)) {
  32534. return null; // null since geometry could be something else than a ground...
  32535. }
  32536. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  32537. if (BABYLON.Tags) {
  32538. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  32539. }
  32540. scene.pushGeometry(plane, true);
  32541. return plane;
  32542. };
  32543. return Plane;
  32544. }(_Primitive));
  32545. Primitives.Plane = Plane;
  32546. var TorusKnot = /** @class */ (function (_super) {
  32547. __extends(TorusKnot, _super);
  32548. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  32549. if (mesh === void 0) { mesh = null; }
  32550. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32551. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32552. _this.radius = radius;
  32553. _this.tube = tube;
  32554. _this.radialSegments = radialSegments;
  32555. _this.tubularSegments = tubularSegments;
  32556. _this.p = p;
  32557. _this.q = q;
  32558. _this.side = side;
  32559. return _this;
  32560. }
  32561. TorusKnot.prototype._regenerateVertexData = function () {
  32562. 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 });
  32563. };
  32564. TorusKnot.prototype.copy = function (id) {
  32565. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  32566. };
  32567. TorusKnot.prototype.serialize = function () {
  32568. var serializationObject = _super.prototype.serialize.call(this);
  32569. serializationObject.radius = this.radius;
  32570. serializationObject.tube = this.tube;
  32571. serializationObject.radialSegments = this.radialSegments;
  32572. serializationObject.tubularSegments = this.tubularSegments;
  32573. serializationObject.p = this.p;
  32574. serializationObject.q = this.q;
  32575. return serializationObject;
  32576. };
  32577. ;
  32578. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  32579. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  32580. return null; // null since geometry could be something else than a ground...
  32581. }
  32582. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  32583. if (BABYLON.Tags) {
  32584. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  32585. }
  32586. scene.pushGeometry(torusKnot, true);
  32587. return torusKnot;
  32588. };
  32589. return TorusKnot;
  32590. }(_Primitive));
  32591. Primitives.TorusKnot = TorusKnot;
  32592. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  32593. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  32594. })(BABYLON || (BABYLON = {}));
  32595. //# sourceMappingURL=babylon.geometry.js.map
  32596. var BABYLON;
  32597. (function (BABYLON) {
  32598. var PostProcessManager = /** @class */ (function () {
  32599. function PostProcessManager(scene) {
  32600. this._vertexBuffers = {};
  32601. this._scene = scene;
  32602. }
  32603. PostProcessManager.prototype._prepareBuffers = function () {
  32604. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  32605. return;
  32606. }
  32607. // VBO
  32608. var vertices = [];
  32609. vertices.push(1, 1);
  32610. vertices.push(-1, 1);
  32611. vertices.push(-1, -1);
  32612. vertices.push(1, -1);
  32613. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  32614. this._buildIndexBuffer();
  32615. };
  32616. PostProcessManager.prototype._buildIndexBuffer = function () {
  32617. // Indices
  32618. var indices = [];
  32619. indices.push(0);
  32620. indices.push(1);
  32621. indices.push(2);
  32622. indices.push(0);
  32623. indices.push(2);
  32624. indices.push(3);
  32625. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  32626. };
  32627. PostProcessManager.prototype._rebuild = function () {
  32628. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32629. if (!vb) {
  32630. return;
  32631. }
  32632. vb._rebuild();
  32633. this._buildIndexBuffer();
  32634. };
  32635. // Methods
  32636. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  32637. if (sourceTexture === void 0) { sourceTexture = null; }
  32638. if (postProcesses === void 0) { postProcesses = null; }
  32639. var camera = this._scene.activeCamera;
  32640. if (!camera) {
  32641. return false;
  32642. }
  32643. var postProcesses = postProcesses || camera._postProcesses;
  32644. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  32645. return false;
  32646. }
  32647. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  32648. return true;
  32649. };
  32650. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  32651. if (targetTexture === void 0) { targetTexture = null; }
  32652. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  32653. var engine = this._scene.getEngine();
  32654. for (var index = 0; index < postProcesses.length; index++) {
  32655. if (index < postProcesses.length - 1) {
  32656. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  32657. }
  32658. else {
  32659. if (targetTexture) {
  32660. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  32661. }
  32662. else {
  32663. engine.restoreDefaultFramebuffer();
  32664. }
  32665. }
  32666. var pp = postProcesses[index];
  32667. var effect = pp.apply();
  32668. if (effect) {
  32669. pp.onBeforeRenderObservable.notifyObservers(effect);
  32670. // VBOs
  32671. this._prepareBuffers();
  32672. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32673. // Draw order
  32674. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  32675. pp.onAfterRenderObservable.notifyObservers(effect);
  32676. }
  32677. }
  32678. // Restore depth buffer
  32679. engine.setDepthBuffer(true);
  32680. engine.setDepthWrite(true);
  32681. };
  32682. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  32683. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  32684. var camera = this._scene.activeCamera;
  32685. if (!camera) {
  32686. return;
  32687. }
  32688. postProcesses = postProcesses || camera._postProcesses;
  32689. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  32690. return;
  32691. }
  32692. var engine = this._scene.getEngine();
  32693. for (var index = 0, len = postProcesses.length; index < len; index++) {
  32694. if (index < len - 1) {
  32695. postProcesses[index + 1].activate(camera, targetTexture);
  32696. }
  32697. else {
  32698. if (targetTexture) {
  32699. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  32700. }
  32701. else {
  32702. engine.restoreDefaultFramebuffer();
  32703. }
  32704. }
  32705. if (doNotPresent) {
  32706. break;
  32707. }
  32708. var pp = postProcesses[index];
  32709. var effect = pp.apply();
  32710. if (effect) {
  32711. pp.onBeforeRenderObservable.notifyObservers(effect);
  32712. // VBOs
  32713. this._prepareBuffers();
  32714. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32715. // Draw order
  32716. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  32717. pp.onAfterRenderObservable.notifyObservers(effect);
  32718. }
  32719. }
  32720. // Restore states
  32721. engine.setDepthBuffer(true);
  32722. engine.setDepthWrite(true);
  32723. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32724. };
  32725. PostProcessManager.prototype.dispose = function () {
  32726. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32727. if (buffer) {
  32728. buffer.dispose();
  32729. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  32730. }
  32731. if (this._indexBuffer) {
  32732. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32733. this._indexBuffer = null;
  32734. }
  32735. };
  32736. return PostProcessManager;
  32737. }());
  32738. BABYLON.PostProcessManager = PostProcessManager;
  32739. })(BABYLON || (BABYLON = {}));
  32740. //# sourceMappingURL=babylon.postProcessManager.js.map
  32741. var BABYLON;
  32742. (function (BABYLON) {
  32743. /**
  32744. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  32745. */
  32746. var PerformanceMonitor = /** @class */ (function () {
  32747. /**
  32748. * constructor
  32749. * @param frameSampleSize The number of samples required to saturate the sliding window
  32750. */
  32751. function PerformanceMonitor(frameSampleSize) {
  32752. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  32753. this._enabled = true;
  32754. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  32755. }
  32756. /**
  32757. * Samples current frame
  32758. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  32759. */
  32760. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  32761. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  32762. if (!this._enabled)
  32763. return;
  32764. if (this._lastFrameTimeMs != null) {
  32765. var dt = timeMs - this._lastFrameTimeMs;
  32766. this._rollingFrameTime.add(dt);
  32767. }
  32768. this._lastFrameTimeMs = timeMs;
  32769. };
  32770. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  32771. /**
  32772. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  32773. * @return Average frame time in milliseconds
  32774. */
  32775. get: function () {
  32776. return this._rollingFrameTime.average;
  32777. },
  32778. enumerable: true,
  32779. configurable: true
  32780. });
  32781. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  32782. /**
  32783. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  32784. * @return Frame time variance in milliseconds squared
  32785. */
  32786. get: function () {
  32787. return this._rollingFrameTime.variance;
  32788. },
  32789. enumerable: true,
  32790. configurable: true
  32791. });
  32792. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  32793. /**
  32794. * Returns the frame time of the most recent frame
  32795. * @return Frame time in milliseconds
  32796. */
  32797. get: function () {
  32798. return this._rollingFrameTime.history(0);
  32799. },
  32800. enumerable: true,
  32801. configurable: true
  32802. });
  32803. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  32804. /**
  32805. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  32806. * @return Framerate in frames per second
  32807. */
  32808. get: function () {
  32809. return 1000.0 / this._rollingFrameTime.average;
  32810. },
  32811. enumerable: true,
  32812. configurable: true
  32813. });
  32814. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  32815. /**
  32816. * Returns the average framerate in frames per second using the most recent frame time
  32817. * @return Framerate in frames per second
  32818. */
  32819. get: function () {
  32820. var history = this._rollingFrameTime.history(0);
  32821. if (history === 0) {
  32822. return 0;
  32823. }
  32824. return 1000.0 / history;
  32825. },
  32826. enumerable: true,
  32827. configurable: true
  32828. });
  32829. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  32830. /**
  32831. * Returns true if enough samples have been taken to completely fill the sliding window
  32832. * @return true if saturated
  32833. */
  32834. get: function () {
  32835. return this._rollingFrameTime.isSaturated();
  32836. },
  32837. enumerable: true,
  32838. configurable: true
  32839. });
  32840. /**
  32841. * Enables contributions to the sliding window sample set
  32842. */
  32843. PerformanceMonitor.prototype.enable = function () {
  32844. this._enabled = true;
  32845. };
  32846. /**
  32847. * Disables contributions to the sliding window sample set
  32848. * Samples will not be interpolated over the disabled period
  32849. */
  32850. PerformanceMonitor.prototype.disable = function () {
  32851. this._enabled = false;
  32852. //clear last sample to avoid interpolating over the disabled period when next enabled
  32853. this._lastFrameTimeMs = null;
  32854. };
  32855. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  32856. /**
  32857. * Returns true if sampling is enabled
  32858. * @return true if enabled
  32859. */
  32860. get: function () {
  32861. return this._enabled;
  32862. },
  32863. enumerable: true,
  32864. configurable: true
  32865. });
  32866. /**
  32867. * Resets performance monitor
  32868. */
  32869. PerformanceMonitor.prototype.reset = function () {
  32870. //clear last sample to avoid interpolating over the disabled period when next enabled
  32871. this._lastFrameTimeMs = null;
  32872. //wipe record
  32873. this._rollingFrameTime.reset();
  32874. };
  32875. return PerformanceMonitor;
  32876. }());
  32877. BABYLON.PerformanceMonitor = PerformanceMonitor;
  32878. /**
  32879. * RollingAverage
  32880. *
  32881. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  32882. */
  32883. var RollingAverage = /** @class */ (function () {
  32884. /**
  32885. * constructor
  32886. * @param length The number of samples required to saturate the sliding window
  32887. */
  32888. function RollingAverage(length) {
  32889. this._samples = new Array(length);
  32890. this.reset();
  32891. }
  32892. /**
  32893. * Adds a sample to the sample set
  32894. * @param v The sample value
  32895. */
  32896. RollingAverage.prototype.add = function (v) {
  32897. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  32898. var delta;
  32899. //we need to check if we've already wrapped round
  32900. if (this.isSaturated()) {
  32901. //remove bottom of stack from mean
  32902. var bottomValue = this._samples[this._pos];
  32903. delta = bottomValue - this.average;
  32904. this.average -= delta / (this._sampleCount - 1);
  32905. this._m2 -= delta * (bottomValue - this.average);
  32906. }
  32907. else {
  32908. this._sampleCount++;
  32909. }
  32910. //add new value to mean
  32911. delta = v - this.average;
  32912. this.average += delta / (this._sampleCount);
  32913. this._m2 += delta * (v - this.average);
  32914. //set the new variance
  32915. this.variance = this._m2 / (this._sampleCount - 1);
  32916. this._samples[this._pos] = v;
  32917. this._pos++;
  32918. this._pos %= this._samples.length; //positive wrap around
  32919. };
  32920. /**
  32921. * Returns previously added values or null if outside of history or outside the sliding window domain
  32922. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  32923. * @return Value previously recorded with add() or null if outside of range
  32924. */
  32925. RollingAverage.prototype.history = function (i) {
  32926. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  32927. return 0;
  32928. }
  32929. var i0 = this._wrapPosition(this._pos - 1.0);
  32930. return this._samples[this._wrapPosition(i0 - i)];
  32931. };
  32932. /**
  32933. * Returns true if enough samples have been taken to completely fill the sliding window
  32934. * @return true if sample-set saturated
  32935. */
  32936. RollingAverage.prototype.isSaturated = function () {
  32937. return this._sampleCount >= this._samples.length;
  32938. };
  32939. /**
  32940. * Resets the rolling average (equivalent to 0 samples taken so far)
  32941. */
  32942. RollingAverage.prototype.reset = function () {
  32943. this.average = 0;
  32944. this.variance = 0;
  32945. this._sampleCount = 0;
  32946. this._pos = 0;
  32947. this._m2 = 0;
  32948. };
  32949. /**
  32950. * Wraps a value around the sample range boundaries
  32951. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  32952. * @return Wrapped position in sample range
  32953. */
  32954. RollingAverage.prototype._wrapPosition = function (i) {
  32955. var max = this._samples.length;
  32956. return ((i % max) + max) % max;
  32957. };
  32958. return RollingAverage;
  32959. }());
  32960. BABYLON.RollingAverage = RollingAverage;
  32961. })(BABYLON || (BABYLON = {}));
  32962. //# sourceMappingURL=babylon.performanceMonitor.js.map
  32963. var BABYLON;
  32964. (function (BABYLON) {
  32965. /**
  32966. * This groups together the common properties used for image processing either in direct forward pass
  32967. * or through post processing effect depending on the use of the image processing pipeline in your scene
  32968. * or not.
  32969. */
  32970. var ImageProcessingConfiguration = /** @class */ (function () {
  32971. function ImageProcessingConfiguration() {
  32972. /**
  32973. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  32974. */
  32975. this.colorCurves = new BABYLON.ColorCurves();
  32976. this._colorCurvesEnabled = false;
  32977. this._colorGradingEnabled = false;
  32978. this._colorGradingWithGreenDepth = true;
  32979. this._colorGradingBGR = true;
  32980. this._exposure = 1.0;
  32981. this._toneMappingEnabled = false;
  32982. this._contrast = 1.0;
  32983. /**
  32984. * Vignette stretch size.
  32985. */
  32986. this.vignetteStretch = 0;
  32987. /**
  32988. * Vignette centre X Offset.
  32989. */
  32990. this.vignetteCentreX = 0;
  32991. /**
  32992. * Vignette centre Y Offset.
  32993. */
  32994. this.vignetteCentreY = 0;
  32995. /**
  32996. * Vignette weight or intensity of the vignette effect.
  32997. */
  32998. this.vignetteWeight = 1.5;
  32999. /**
  33000. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  33001. * if vignetteEnabled is set to true.
  33002. */
  33003. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  33004. /**
  33005. * Camera field of view used by the Vignette effect.
  33006. */
  33007. this.vignetteCameraFov = 0.5;
  33008. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  33009. this._vignetteEnabled = false;
  33010. this._applyByPostProcess = false;
  33011. this._isEnabled = true;
  33012. /**
  33013. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  33014. * @type {BABYLON.Observable}
  33015. */
  33016. this.onUpdateParameters = new BABYLON.Observable();
  33017. }
  33018. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  33019. /**
  33020. * Gets wether the color curves effect is enabled.
  33021. */
  33022. get: function () {
  33023. return this._colorCurvesEnabled;
  33024. },
  33025. /**
  33026. * Sets wether the color curves effect is enabled.
  33027. */
  33028. set: function (value) {
  33029. if (this._colorCurvesEnabled === value) {
  33030. return;
  33031. }
  33032. this._colorCurvesEnabled = value;
  33033. this._updateParameters();
  33034. },
  33035. enumerable: true,
  33036. configurable: true
  33037. });
  33038. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  33039. /**
  33040. * Gets wether the color grading effect is enabled.
  33041. */
  33042. get: function () {
  33043. return this._colorGradingEnabled;
  33044. },
  33045. /**
  33046. * Sets wether the color grading effect is enabled.
  33047. */
  33048. set: function (value) {
  33049. if (this._colorGradingEnabled === value) {
  33050. return;
  33051. }
  33052. this._colorGradingEnabled = value;
  33053. this._updateParameters();
  33054. },
  33055. enumerable: true,
  33056. configurable: true
  33057. });
  33058. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  33059. /**
  33060. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  33061. */
  33062. get: function () {
  33063. return this._colorGradingWithGreenDepth;
  33064. },
  33065. /**
  33066. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  33067. */
  33068. set: function (value) {
  33069. if (this._colorGradingWithGreenDepth === value) {
  33070. return;
  33071. }
  33072. this._colorGradingWithGreenDepth = value;
  33073. this._updateParameters();
  33074. },
  33075. enumerable: true,
  33076. configurable: true
  33077. });
  33078. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  33079. /**
  33080. * Gets wether the color grading texture contains BGR values.
  33081. */
  33082. get: function () {
  33083. return this._colorGradingBGR;
  33084. },
  33085. /**
  33086. * Sets wether the color grading texture contains BGR values.
  33087. */
  33088. set: function (value) {
  33089. if (this._colorGradingBGR === value) {
  33090. return;
  33091. }
  33092. this._colorGradingBGR = value;
  33093. this._updateParameters();
  33094. },
  33095. enumerable: true,
  33096. configurable: true
  33097. });
  33098. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  33099. /**
  33100. * Gets the Exposure used in the effect.
  33101. */
  33102. get: function () {
  33103. return this._exposure;
  33104. },
  33105. /**
  33106. * Sets the Exposure used in the effect.
  33107. */
  33108. set: function (value) {
  33109. if (this._exposure === value) {
  33110. return;
  33111. }
  33112. this._exposure = value;
  33113. this._updateParameters();
  33114. },
  33115. enumerable: true,
  33116. configurable: true
  33117. });
  33118. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  33119. /**
  33120. * Gets wether the tone mapping effect is enabled.
  33121. */
  33122. get: function () {
  33123. return this._toneMappingEnabled;
  33124. },
  33125. /**
  33126. * Sets wether the tone mapping effect is enabled.
  33127. */
  33128. set: function (value) {
  33129. if (this._toneMappingEnabled === value) {
  33130. return;
  33131. }
  33132. this._toneMappingEnabled = value;
  33133. this._updateParameters();
  33134. },
  33135. enumerable: true,
  33136. configurable: true
  33137. });
  33138. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  33139. /**
  33140. * Gets the contrast used in the effect.
  33141. */
  33142. get: function () {
  33143. return this._contrast;
  33144. },
  33145. /**
  33146. * Sets the contrast used in the effect.
  33147. */
  33148. set: function (value) {
  33149. if (this._contrast === value) {
  33150. return;
  33151. }
  33152. this._contrast = value;
  33153. this._updateParameters();
  33154. },
  33155. enumerable: true,
  33156. configurable: true
  33157. });
  33158. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  33159. /**
  33160. * Gets the vignette blend mode allowing different kind of effect.
  33161. */
  33162. get: function () {
  33163. return this._vignetteBlendMode;
  33164. },
  33165. /**
  33166. * Sets the vignette blend mode allowing different kind of effect.
  33167. */
  33168. set: function (value) {
  33169. if (this._vignetteBlendMode === value) {
  33170. return;
  33171. }
  33172. this._vignetteBlendMode = value;
  33173. this._updateParameters();
  33174. },
  33175. enumerable: true,
  33176. configurable: true
  33177. });
  33178. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  33179. /**
  33180. * Gets wether the vignette effect is enabled.
  33181. */
  33182. get: function () {
  33183. return this._vignetteEnabled;
  33184. },
  33185. /**
  33186. * Sets wether the vignette effect is enabled.
  33187. */
  33188. set: function (value) {
  33189. if (this._vignetteEnabled === value) {
  33190. return;
  33191. }
  33192. this._vignetteEnabled = value;
  33193. this._updateParameters();
  33194. },
  33195. enumerable: true,
  33196. configurable: true
  33197. });
  33198. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  33199. /**
  33200. * Gets wether the image processing is applied through a post process or not.
  33201. */
  33202. get: function () {
  33203. return this._applyByPostProcess;
  33204. },
  33205. /**
  33206. * Sets wether the image processing is applied through a post process or not.
  33207. */
  33208. set: function (value) {
  33209. if (this._applyByPostProcess === value) {
  33210. return;
  33211. }
  33212. this._applyByPostProcess = value;
  33213. this._updateParameters();
  33214. },
  33215. enumerable: true,
  33216. configurable: true
  33217. });
  33218. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  33219. /**
  33220. * Gets wether the image processing is enabled or not.
  33221. */
  33222. get: function () {
  33223. return this._isEnabled;
  33224. },
  33225. /**
  33226. * Sets wether the image processing is enabled or not.
  33227. */
  33228. set: function (value) {
  33229. if (this._isEnabled === value) {
  33230. return;
  33231. }
  33232. this._isEnabled = value;
  33233. this._updateParameters();
  33234. },
  33235. enumerable: true,
  33236. configurable: true
  33237. });
  33238. /**
  33239. * Method called each time the image processing information changes requires to recompile the effect.
  33240. */
  33241. ImageProcessingConfiguration.prototype._updateParameters = function () {
  33242. this.onUpdateParameters.notifyObservers(this);
  33243. };
  33244. ImageProcessingConfiguration.prototype.getClassName = function () {
  33245. return "ImageProcessingConfiguration";
  33246. };
  33247. /**
  33248. * Prepare the list of uniforms associated with the Image Processing effects.
  33249. * @param uniformsList The list of uniforms used in the effect
  33250. * @param defines the list of defines currently in use
  33251. */
  33252. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  33253. if (defines.EXPOSURE) {
  33254. uniforms.push("exposureLinear");
  33255. }
  33256. if (defines.CONTRAST) {
  33257. uniforms.push("contrast");
  33258. }
  33259. if (defines.COLORGRADING) {
  33260. uniforms.push("colorTransformSettings");
  33261. }
  33262. if (defines.VIGNETTE) {
  33263. uniforms.push("vInverseScreenSize");
  33264. uniforms.push("vignetteSettings1");
  33265. uniforms.push("vignetteSettings2");
  33266. }
  33267. if (defines.COLORCURVES) {
  33268. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  33269. }
  33270. };
  33271. /**
  33272. * Prepare the list of samplers associated with the Image Processing effects.
  33273. * @param uniformsList The list of uniforms used in the effect
  33274. * @param defines the list of defines currently in use
  33275. */
  33276. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  33277. if (defines.COLORGRADING) {
  33278. samplersList.push("txColorTransform");
  33279. }
  33280. };
  33281. /**
  33282. * Prepare the list of defines associated to the shader.
  33283. * @param defines the list of defines to complete
  33284. */
  33285. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  33286. if (forPostProcess === void 0) { forPostProcess = false; }
  33287. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  33288. defines.VIGNETTE = false;
  33289. defines.TONEMAPPING = false;
  33290. defines.CONTRAST = false;
  33291. defines.EXPOSURE = false;
  33292. defines.COLORCURVES = false;
  33293. defines.COLORGRADING = false;
  33294. defines.COLORGRADING3D = false;
  33295. defines.IMAGEPROCESSING = false;
  33296. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  33297. return;
  33298. }
  33299. defines.VIGNETTE = this.vignetteEnabled;
  33300. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  33301. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  33302. defines.TONEMAPPING = this.toneMappingEnabled;
  33303. defines.CONTRAST = (this.contrast !== 1.0);
  33304. defines.EXPOSURE = (this.exposure !== 1.0);
  33305. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  33306. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  33307. if (defines.COLORGRADING) {
  33308. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  33309. }
  33310. else {
  33311. defines.COLORGRADING3D = false;
  33312. }
  33313. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  33314. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  33315. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  33316. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  33317. };
  33318. /**
  33319. * Returns true if all the image processing information are ready.
  33320. */
  33321. ImageProcessingConfiguration.prototype.isReady = function () {
  33322. // Color Grading texure can not be none blocking.
  33323. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  33324. };
  33325. /**
  33326. * Binds the image processing to the shader.
  33327. * @param effect The effect to bind to
  33328. */
  33329. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  33330. if (aspectRatio === void 0) { aspectRatio = 1; }
  33331. // Color Curves
  33332. if (this._colorCurvesEnabled && this.colorCurves) {
  33333. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  33334. }
  33335. // Vignette
  33336. if (this._vignetteEnabled) {
  33337. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  33338. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  33339. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  33340. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  33341. var vignetteScaleX = vignetteScaleY * aspectRatio;
  33342. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  33343. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  33344. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  33345. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  33346. var vignettePower = -2.0 * this.vignetteWeight;
  33347. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  33348. }
  33349. // Exposure
  33350. effect.setFloat("exposureLinear", this.exposure);
  33351. // Contrast
  33352. effect.setFloat("contrast", this.contrast);
  33353. // Color transform settings
  33354. if (this.colorGradingTexture) {
  33355. effect.setTexture("txColorTransform", this.colorGradingTexture);
  33356. var textureSize = this.colorGradingTexture.getSize().height;
  33357. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  33358. 0.5 / textureSize, // textureOffset
  33359. textureSize, // textureSize
  33360. this.colorGradingTexture.level // weight
  33361. );
  33362. }
  33363. };
  33364. /**
  33365. * Clones the current image processing instance.
  33366. * @return The cloned image processing
  33367. */
  33368. ImageProcessingConfiguration.prototype.clone = function () {
  33369. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  33370. };
  33371. /**
  33372. * Serializes the current image processing instance to a json representation.
  33373. * @return a JSON representation
  33374. */
  33375. ImageProcessingConfiguration.prototype.serialize = function () {
  33376. return BABYLON.SerializationHelper.Serialize(this);
  33377. };
  33378. /**
  33379. * Parses the image processing from a json representation.
  33380. * @param source the JSON source to parse
  33381. * @return The parsed image processing
  33382. */
  33383. ImageProcessingConfiguration.Parse = function (source) {
  33384. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  33385. };
  33386. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  33387. /**
  33388. * Used to apply the vignette as a mix with the pixel color.
  33389. */
  33390. get: function () {
  33391. return this._VIGNETTEMODE_MULTIPLY;
  33392. },
  33393. enumerable: true,
  33394. configurable: true
  33395. });
  33396. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  33397. /**
  33398. * Used to apply the vignette as a replacement of the pixel color.
  33399. */
  33400. get: function () {
  33401. return this._VIGNETTEMODE_OPAQUE;
  33402. },
  33403. enumerable: true,
  33404. configurable: true
  33405. });
  33406. // Static constants associated to the image processing.
  33407. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  33408. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  33409. __decorate([
  33410. BABYLON.serializeAsColorCurves()
  33411. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  33412. __decorate([
  33413. BABYLON.serialize()
  33414. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  33415. __decorate([
  33416. BABYLON.serializeAsTexture()
  33417. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  33418. __decorate([
  33419. BABYLON.serialize()
  33420. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  33421. __decorate([
  33422. BABYLON.serialize()
  33423. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  33424. __decorate([
  33425. BABYLON.serialize()
  33426. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  33427. __decorate([
  33428. BABYLON.serialize()
  33429. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  33430. __decorate([
  33431. BABYLON.serialize()
  33432. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  33433. __decorate([
  33434. BABYLON.serialize()
  33435. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  33436. __decorate([
  33437. BABYLON.serialize()
  33438. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  33439. __decorate([
  33440. BABYLON.serialize()
  33441. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  33442. __decorate([
  33443. BABYLON.serialize()
  33444. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  33445. __decorate([
  33446. BABYLON.serialize()
  33447. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  33448. __decorate([
  33449. BABYLON.serializeAsColor4()
  33450. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  33451. __decorate([
  33452. BABYLON.serialize()
  33453. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  33454. __decorate([
  33455. BABYLON.serialize()
  33456. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  33457. __decorate([
  33458. BABYLON.serialize()
  33459. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  33460. __decorate([
  33461. BABYLON.serialize()
  33462. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  33463. __decorate([
  33464. BABYLON.serialize()
  33465. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  33466. return ImageProcessingConfiguration;
  33467. }());
  33468. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  33469. })(BABYLON || (BABYLON = {}));
  33470. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  33471. var BABYLON;
  33472. (function (BABYLON) {
  33473. /**
  33474. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  33475. * It can help converting any input color in a desired output one. This can then be used to create effects
  33476. * from sepia, black and white to sixties or futuristic rendering...
  33477. *
  33478. * The only supported format is currently 3dl.
  33479. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  33480. */
  33481. var ColorGradingTexture = /** @class */ (function (_super) {
  33482. __extends(ColorGradingTexture, _super);
  33483. /**
  33484. * Instantiates a ColorGradingTexture from the following parameters.
  33485. *
  33486. * @param url The location of the color gradind data (currently only supporting 3dl)
  33487. * @param scene The scene the texture will be used in
  33488. */
  33489. function ColorGradingTexture(url, scene) {
  33490. var _this = _super.call(this, scene) || this;
  33491. if (!url) {
  33492. return _this;
  33493. }
  33494. _this._engine = scene.getEngine();
  33495. _this._textureMatrix = BABYLON.Matrix.Identity();
  33496. _this.name = url;
  33497. _this.url = url;
  33498. _this.hasAlpha = false;
  33499. _this.isCube = false;
  33500. _this.is3D = _this._engine.webGLVersion > 1;
  33501. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33502. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33503. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33504. _this.anisotropicFilteringLevel = 1;
  33505. _this._texture = _this._getFromCache(url, true);
  33506. if (!_this._texture) {
  33507. if (!scene.useDelayedTextureLoading) {
  33508. _this.loadTexture();
  33509. }
  33510. else {
  33511. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33512. }
  33513. }
  33514. return _this;
  33515. }
  33516. /**
  33517. * Returns the texture matrix used in most of the material.
  33518. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  33519. */
  33520. ColorGradingTexture.prototype.getTextureMatrix = function () {
  33521. return this._textureMatrix;
  33522. };
  33523. /**
  33524. * Occurs when the file being loaded is a .3dl LUT file.
  33525. */
  33526. ColorGradingTexture.prototype.load3dlTexture = function () {
  33527. var engine = this._engine;
  33528. var texture;
  33529. if (engine.webGLVersion === 1) {
  33530. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33531. }
  33532. else {
  33533. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33534. }
  33535. this._texture = texture;
  33536. var callback = function (text) {
  33537. if (typeof text !== "string") {
  33538. return;
  33539. }
  33540. var data = null;
  33541. var tempData = null;
  33542. var line;
  33543. var lines = text.split('\n');
  33544. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  33545. var maxColor = 0;
  33546. for (var i = 0; i < lines.length; i++) {
  33547. line = lines[i];
  33548. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  33549. continue;
  33550. if (line.indexOf('#') === 0)
  33551. continue;
  33552. var words = line.split(" ");
  33553. if (size === 0) {
  33554. // Number of space + one
  33555. size = words.length;
  33556. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  33557. tempData = new Float32Array(size * size * size * 4);
  33558. continue;
  33559. }
  33560. if (size != 0) {
  33561. var r = Math.max(parseInt(words[0]), 0);
  33562. var g = Math.max(parseInt(words[1]), 0);
  33563. var b = Math.max(parseInt(words[2]), 0);
  33564. maxColor = Math.max(r, maxColor);
  33565. maxColor = Math.max(g, maxColor);
  33566. maxColor = Math.max(b, maxColor);
  33567. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  33568. if (tempData) {
  33569. tempData[pixelStorageIndex + 0] = r;
  33570. tempData[pixelStorageIndex + 1] = g;
  33571. tempData[pixelStorageIndex + 2] = b;
  33572. }
  33573. pixelIndexSlice++;
  33574. if (pixelIndexSlice % size == 0) {
  33575. pixelIndexH++;
  33576. pixelIndexSlice = 0;
  33577. if (pixelIndexH % size == 0) {
  33578. pixelIndexW++;
  33579. pixelIndexH = 0;
  33580. }
  33581. }
  33582. }
  33583. }
  33584. if (tempData && data) {
  33585. for (var i = 0; i < tempData.length; i++) {
  33586. if (i > 0 && (i + 1) % 4 === 0) {
  33587. data[i] = 255;
  33588. }
  33589. else {
  33590. var value = tempData[i];
  33591. data[i] = (value / maxColor * 255);
  33592. }
  33593. }
  33594. }
  33595. if (texture.is3D) {
  33596. texture.updateSize(size, size, size);
  33597. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  33598. }
  33599. else {
  33600. texture.updateSize(size * size, size);
  33601. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  33602. }
  33603. };
  33604. var scene = this.getScene();
  33605. if (scene) {
  33606. scene._loadFile(this.url, callback);
  33607. }
  33608. else {
  33609. this._engine._loadFile(this.url, callback);
  33610. }
  33611. return this._texture;
  33612. };
  33613. /**
  33614. * Starts the loading process of the texture.
  33615. */
  33616. ColorGradingTexture.prototype.loadTexture = function () {
  33617. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  33618. this.load3dlTexture();
  33619. }
  33620. };
  33621. /**
  33622. * Clones the color gradind texture.
  33623. */
  33624. ColorGradingTexture.prototype.clone = function () {
  33625. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  33626. // Base texture
  33627. newTexture.level = this.level;
  33628. return newTexture;
  33629. };
  33630. /**
  33631. * Called during delayed load for textures.
  33632. */
  33633. ColorGradingTexture.prototype.delayLoad = function () {
  33634. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  33635. return;
  33636. }
  33637. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33638. this._texture = this._getFromCache(this.url, true);
  33639. if (!this._texture) {
  33640. this.loadTexture();
  33641. }
  33642. };
  33643. /**
  33644. * Parses a color grading texture serialized by Babylon.
  33645. * @param parsedTexture The texture information being parsedTexture
  33646. * @param scene The scene to load the texture in
  33647. * @param rootUrl The root url of the data assets to load
  33648. * @return A color gradind texture
  33649. */
  33650. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  33651. var texture = null;
  33652. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  33653. texture = new ColorGradingTexture(parsedTexture.name, scene);
  33654. texture.name = parsedTexture.name;
  33655. texture.level = parsedTexture.level;
  33656. }
  33657. return texture;
  33658. };
  33659. /**
  33660. * Serializes the LUT texture to json format.
  33661. */
  33662. ColorGradingTexture.prototype.serialize = function () {
  33663. if (!this.name) {
  33664. return null;
  33665. }
  33666. var serializationObject = {};
  33667. serializationObject.name = this.name;
  33668. serializationObject.level = this.level;
  33669. serializationObject.customType = "BABYLON.ColorGradingTexture";
  33670. return serializationObject;
  33671. };
  33672. /**
  33673. * Empty line regex stored for GC.
  33674. */
  33675. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  33676. return ColorGradingTexture;
  33677. }(BABYLON.BaseTexture));
  33678. BABYLON.ColorGradingTexture = ColorGradingTexture;
  33679. })(BABYLON || (BABYLON = {}));
  33680. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  33681. var BABYLON;
  33682. (function (BABYLON) {
  33683. /**
  33684. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33685. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33686. * 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;
  33687. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33688. */
  33689. var ColorCurves = /** @class */ (function () {
  33690. function ColorCurves() {
  33691. this._dirty = true;
  33692. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  33693. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  33694. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  33695. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  33696. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  33697. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  33698. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  33699. this._globalHue = 30;
  33700. this._globalDensity = 0;
  33701. this._globalSaturation = 0;
  33702. this._globalExposure = 0;
  33703. this._highlightsHue = 30;
  33704. this._highlightsDensity = 0;
  33705. this._highlightsSaturation = 0;
  33706. this._highlightsExposure = 0;
  33707. this._midtonesHue = 30;
  33708. this._midtonesDensity = 0;
  33709. this._midtonesSaturation = 0;
  33710. this._midtonesExposure = 0;
  33711. this._shadowsHue = 30;
  33712. this._shadowsDensity = 0;
  33713. this._shadowsSaturation = 0;
  33714. this._shadowsExposure = 0;
  33715. }
  33716. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  33717. /**
  33718. * Gets the global Hue value.
  33719. * 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).
  33720. */
  33721. get: function () {
  33722. return this._globalHue;
  33723. },
  33724. /**
  33725. * Sets the global Hue value.
  33726. * 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).
  33727. */
  33728. set: function (value) {
  33729. this._globalHue = value;
  33730. this._dirty = true;
  33731. },
  33732. enumerable: true,
  33733. configurable: true
  33734. });
  33735. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  33736. /**
  33737. * Gets the global Density value.
  33738. * 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.
  33739. * Values less than zero provide a filter of opposite hue.
  33740. */
  33741. get: function () {
  33742. return this._globalDensity;
  33743. },
  33744. /**
  33745. * Sets the global Density value.
  33746. * 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.
  33747. * Values less than zero provide a filter of opposite hue.
  33748. */
  33749. set: function (value) {
  33750. this._globalDensity = value;
  33751. this._dirty = true;
  33752. },
  33753. enumerable: true,
  33754. configurable: true
  33755. });
  33756. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  33757. /**
  33758. * Gets the global Saturation value.
  33759. * 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.
  33760. */
  33761. get: function () {
  33762. return this._globalSaturation;
  33763. },
  33764. /**
  33765. * Sets the global Saturation value.
  33766. * 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.
  33767. */
  33768. set: function (value) {
  33769. this._globalSaturation = value;
  33770. this._dirty = true;
  33771. },
  33772. enumerable: true,
  33773. configurable: true
  33774. });
  33775. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  33776. /**
  33777. * Gets the highlights Hue value.
  33778. * 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).
  33779. */
  33780. get: function () {
  33781. return this._highlightsHue;
  33782. },
  33783. /**
  33784. * Sets the highlights Hue value.
  33785. * 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).
  33786. */
  33787. set: function (value) {
  33788. this._highlightsHue = value;
  33789. this._dirty = true;
  33790. },
  33791. enumerable: true,
  33792. configurable: true
  33793. });
  33794. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  33795. /**
  33796. * Gets the highlights Density value.
  33797. * 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.
  33798. * Values less than zero provide a filter of opposite hue.
  33799. */
  33800. get: function () {
  33801. return this._highlightsDensity;
  33802. },
  33803. /**
  33804. * Sets the highlights Density value.
  33805. * 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.
  33806. * Values less than zero provide a filter of opposite hue.
  33807. */
  33808. set: function (value) {
  33809. this._highlightsDensity = value;
  33810. this._dirty = true;
  33811. },
  33812. enumerable: true,
  33813. configurable: true
  33814. });
  33815. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  33816. /**
  33817. * Gets the highlights Saturation value.
  33818. * 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.
  33819. */
  33820. get: function () {
  33821. return this._highlightsSaturation;
  33822. },
  33823. /**
  33824. * Sets the highlights Saturation value.
  33825. * 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.
  33826. */
  33827. set: function (value) {
  33828. this._highlightsSaturation = value;
  33829. this._dirty = true;
  33830. },
  33831. enumerable: true,
  33832. configurable: true
  33833. });
  33834. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  33835. /**
  33836. * Gets the highlights Exposure value.
  33837. * 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.
  33838. */
  33839. get: function () {
  33840. return this._highlightsExposure;
  33841. },
  33842. /**
  33843. * Sets the highlights Exposure value.
  33844. * 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.
  33845. */
  33846. set: function (value) {
  33847. this._highlightsExposure = value;
  33848. this._dirty = true;
  33849. },
  33850. enumerable: true,
  33851. configurable: true
  33852. });
  33853. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  33854. /**
  33855. * Gets the midtones Hue value.
  33856. * 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).
  33857. */
  33858. get: function () {
  33859. return this._midtonesHue;
  33860. },
  33861. /**
  33862. * Sets the midtones Hue value.
  33863. * 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).
  33864. */
  33865. set: function (value) {
  33866. this._midtonesHue = value;
  33867. this._dirty = true;
  33868. },
  33869. enumerable: true,
  33870. configurable: true
  33871. });
  33872. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  33873. /**
  33874. * Gets the midtones Density value.
  33875. * 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.
  33876. * Values less than zero provide a filter of opposite hue.
  33877. */
  33878. get: function () {
  33879. return this._midtonesDensity;
  33880. },
  33881. /**
  33882. * Sets the midtones Density value.
  33883. * 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.
  33884. * Values less than zero provide a filter of opposite hue.
  33885. */
  33886. set: function (value) {
  33887. this._midtonesDensity = value;
  33888. this._dirty = true;
  33889. },
  33890. enumerable: true,
  33891. configurable: true
  33892. });
  33893. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  33894. /**
  33895. * Gets the midtones Saturation value.
  33896. * 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.
  33897. */
  33898. get: function () {
  33899. return this._midtonesSaturation;
  33900. },
  33901. /**
  33902. * Sets the midtones Saturation value.
  33903. * 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.
  33904. */
  33905. set: function (value) {
  33906. this._midtonesSaturation = value;
  33907. this._dirty = true;
  33908. },
  33909. enumerable: true,
  33910. configurable: true
  33911. });
  33912. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  33913. /**
  33914. * Gets the midtones Exposure value.
  33915. * 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.
  33916. */
  33917. get: function () {
  33918. return this._midtonesExposure;
  33919. },
  33920. /**
  33921. * Sets the midtones Exposure value.
  33922. * 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.
  33923. */
  33924. set: function (value) {
  33925. this._midtonesExposure = value;
  33926. this._dirty = true;
  33927. },
  33928. enumerable: true,
  33929. configurable: true
  33930. });
  33931. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  33932. /**
  33933. * Gets the shadows Hue value.
  33934. * 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).
  33935. */
  33936. get: function () {
  33937. return this._shadowsHue;
  33938. },
  33939. /**
  33940. * Sets the shadows Hue value.
  33941. * 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).
  33942. */
  33943. set: function (value) {
  33944. this._shadowsHue = value;
  33945. this._dirty = true;
  33946. },
  33947. enumerable: true,
  33948. configurable: true
  33949. });
  33950. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  33951. /**
  33952. * Gets the shadows Density value.
  33953. * 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.
  33954. * Values less than zero provide a filter of opposite hue.
  33955. */
  33956. get: function () {
  33957. return this._shadowsDensity;
  33958. },
  33959. /**
  33960. * Sets the shadows Density value.
  33961. * 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.
  33962. * Values less than zero provide a filter of opposite hue.
  33963. */
  33964. set: function (value) {
  33965. this._shadowsDensity = value;
  33966. this._dirty = true;
  33967. },
  33968. enumerable: true,
  33969. configurable: true
  33970. });
  33971. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  33972. /**
  33973. * Gets the shadows Saturation value.
  33974. * 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.
  33975. */
  33976. get: function () {
  33977. return this._shadowsSaturation;
  33978. },
  33979. /**
  33980. * Sets the shadows Saturation value.
  33981. * 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.
  33982. */
  33983. set: function (value) {
  33984. this._shadowsSaturation = value;
  33985. this._dirty = true;
  33986. },
  33987. enumerable: true,
  33988. configurable: true
  33989. });
  33990. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  33991. /**
  33992. * Gets the shadows Exposure value.
  33993. * 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.
  33994. */
  33995. get: function () {
  33996. return this._shadowsExposure;
  33997. },
  33998. /**
  33999. * Sets the shadows Exposure value.
  34000. * 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.
  34001. */
  34002. set: function (value) {
  34003. this._shadowsExposure = value;
  34004. this._dirty = true;
  34005. },
  34006. enumerable: true,
  34007. configurable: true
  34008. });
  34009. ColorCurves.prototype.getClassName = function () {
  34010. return "ColorCurves";
  34011. };
  34012. /**
  34013. * Binds the color curves to the shader.
  34014. * @param colorCurves The color curve to bind
  34015. * @param effect The effect to bind to
  34016. */
  34017. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  34018. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  34019. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  34020. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  34021. if (colorCurves._dirty) {
  34022. colorCurves._dirty = false;
  34023. // Fill in global info.
  34024. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  34025. // Compute highlights info.
  34026. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  34027. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  34028. // Compute midtones info.
  34029. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  34030. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  34031. // Compute shadows info.
  34032. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  34033. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  34034. // Compute deltas (neutral is midtones).
  34035. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  34036. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  34037. }
  34038. if (effect) {
  34039. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  34040. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  34041. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  34042. }
  34043. };
  34044. /**
  34045. * Prepare the list of uniforms associated with the ColorCurves effects.
  34046. * @param uniformsList The list of uniforms used in the effect
  34047. */
  34048. ColorCurves.PrepareUniforms = function (uniformsList) {
  34049. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  34050. };
  34051. /**
  34052. * Returns color grading data based on a hue, density, saturation and exposure value.
  34053. * @param filterHue The hue of the color filter.
  34054. * @param filterDensity The density of the color filter.
  34055. * @param saturation The saturation.
  34056. * @param exposure The exposure.
  34057. * @param result The result data container.
  34058. */
  34059. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  34060. if (hue == null) {
  34061. return;
  34062. }
  34063. hue = ColorCurves.clamp(hue, 0, 360);
  34064. density = ColorCurves.clamp(density, -100, 100);
  34065. saturation = ColorCurves.clamp(saturation, -100, 100);
  34066. exposure = ColorCurves.clamp(exposure, -100, 100);
  34067. // Remap the slider/config filter density with non-linear mapping and also scale by half
  34068. // so that the maximum filter density is only 50% control. This provides fine control
  34069. // for small values and reasonable range.
  34070. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  34071. density *= 0.5;
  34072. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  34073. if (density < 0) {
  34074. density *= -1;
  34075. hue = (hue + 180) % 360;
  34076. }
  34077. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  34078. result.scaleToRef(2, result);
  34079. result.a = 1 + 0.01 * saturation;
  34080. };
  34081. /**
  34082. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  34083. * @param value The input slider value in range [-100,100].
  34084. * @returns Adjusted value.
  34085. */
  34086. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  34087. value /= 100;
  34088. var x = Math.abs(value);
  34089. x = Math.pow(x, 2);
  34090. if (value < 0) {
  34091. x *= -1;
  34092. }
  34093. x *= 100;
  34094. return x;
  34095. };
  34096. /**
  34097. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  34098. * @param hue The hue (H) input.
  34099. * @param saturation The saturation (S) input.
  34100. * @param brightness The brightness (B) input.
  34101. * @result An RGBA color represented as Vector4.
  34102. */
  34103. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  34104. var h = ColorCurves.clamp(hue, 0, 360);
  34105. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  34106. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  34107. if (s === 0) {
  34108. result.r = v;
  34109. result.g = v;
  34110. result.b = v;
  34111. }
  34112. else {
  34113. // sector 0 to 5
  34114. h /= 60;
  34115. var i = Math.floor(h);
  34116. // fractional part of h
  34117. var f = h - i;
  34118. var p = v * (1 - s);
  34119. var q = v * (1 - s * f);
  34120. var t = v * (1 - s * (1 - f));
  34121. switch (i) {
  34122. case 0:
  34123. result.r = v;
  34124. result.g = t;
  34125. result.b = p;
  34126. break;
  34127. case 1:
  34128. result.r = q;
  34129. result.g = v;
  34130. result.b = p;
  34131. break;
  34132. case 2:
  34133. result.r = p;
  34134. result.g = v;
  34135. result.b = t;
  34136. break;
  34137. case 3:
  34138. result.r = p;
  34139. result.g = q;
  34140. result.b = v;
  34141. break;
  34142. case 4:
  34143. result.r = t;
  34144. result.g = p;
  34145. result.b = v;
  34146. break;
  34147. default:// case 5:
  34148. result.r = v;
  34149. result.g = p;
  34150. result.b = q;
  34151. break;
  34152. }
  34153. }
  34154. result.a = 1;
  34155. };
  34156. /**
  34157. * Returns a value clamped between min and max
  34158. * @param value The value to clamp
  34159. * @param min The minimum of value
  34160. * @param max The maximum of value
  34161. * @returns The clamped value.
  34162. */
  34163. ColorCurves.clamp = function (value, min, max) {
  34164. return Math.min(Math.max(value, min), max);
  34165. };
  34166. /**
  34167. * Clones the current color curve instance.
  34168. * @return The cloned curves
  34169. */
  34170. ColorCurves.prototype.clone = function () {
  34171. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  34172. };
  34173. /**
  34174. * Serializes the current color curve instance to a json representation.
  34175. * @return a JSON representation
  34176. */
  34177. ColorCurves.prototype.serialize = function () {
  34178. return BABYLON.SerializationHelper.Serialize(this);
  34179. };
  34180. /**
  34181. * Parses the color curve from a json representation.
  34182. * @param source the JSON source to parse
  34183. * @return The parsed curves
  34184. */
  34185. ColorCurves.Parse = function (source) {
  34186. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  34187. };
  34188. __decorate([
  34189. BABYLON.serialize()
  34190. ], ColorCurves.prototype, "_globalHue", void 0);
  34191. __decorate([
  34192. BABYLON.serialize()
  34193. ], ColorCurves.prototype, "_globalDensity", void 0);
  34194. __decorate([
  34195. BABYLON.serialize()
  34196. ], ColorCurves.prototype, "_globalSaturation", void 0);
  34197. __decorate([
  34198. BABYLON.serialize()
  34199. ], ColorCurves.prototype, "_globalExposure", void 0);
  34200. __decorate([
  34201. BABYLON.serialize()
  34202. ], ColorCurves.prototype, "_highlightsHue", void 0);
  34203. __decorate([
  34204. BABYLON.serialize()
  34205. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  34206. __decorate([
  34207. BABYLON.serialize()
  34208. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  34209. __decorate([
  34210. BABYLON.serialize()
  34211. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  34212. __decorate([
  34213. BABYLON.serialize()
  34214. ], ColorCurves.prototype, "_midtonesHue", void 0);
  34215. __decorate([
  34216. BABYLON.serialize()
  34217. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  34218. __decorate([
  34219. BABYLON.serialize()
  34220. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  34221. __decorate([
  34222. BABYLON.serialize()
  34223. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  34224. return ColorCurves;
  34225. }());
  34226. BABYLON.ColorCurves = ColorCurves;
  34227. })(BABYLON || (BABYLON = {}));
  34228. //# sourceMappingURL=babylon.colorCurves.js.map
  34229. var BABYLON;
  34230. (function (BABYLON) {
  34231. var MaterialHelper = /** @class */ (function () {
  34232. function MaterialHelper() {
  34233. }
  34234. MaterialHelper.BindEyePosition = function (effect, scene) {
  34235. if (scene._forcedViewPosition) {
  34236. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  34237. return;
  34238. }
  34239. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  34240. };
  34241. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  34242. defines._needUVs = true;
  34243. defines[key] = true;
  34244. if (texture.getTextureMatrix().isIdentity(true)) {
  34245. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  34246. if (texture.coordinatesIndex === 0) {
  34247. defines["MAINUV1"] = true;
  34248. }
  34249. else {
  34250. defines["MAINUV2"] = true;
  34251. }
  34252. }
  34253. else {
  34254. defines[key + "DIRECTUV"] = 0;
  34255. }
  34256. };
  34257. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  34258. var matrix = texture.getTextureMatrix();
  34259. if (!matrix.isIdentity(true)) {
  34260. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  34261. }
  34262. };
  34263. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  34264. if (defines._areMiscDirty) {
  34265. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  34266. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  34267. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  34268. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  34269. }
  34270. };
  34271. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  34272. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  34273. var changed = false;
  34274. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  34275. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  34276. changed = true;
  34277. }
  34278. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  34279. defines["ALPHATEST"] = !defines["ALPHATEST"];
  34280. changed = true;
  34281. }
  34282. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  34283. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  34284. changed = true;
  34285. }
  34286. if (defines["INSTANCES"] !== useInstances) {
  34287. defines["INSTANCES"] = useInstances;
  34288. changed = true;
  34289. }
  34290. if (changed) {
  34291. defines.markAsUnprocessed();
  34292. }
  34293. };
  34294. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  34295. if (useMorphTargets === void 0) { useMorphTargets = false; }
  34296. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  34297. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  34298. return false;
  34299. }
  34300. defines._normals = defines._needNormals;
  34301. defines._uvs = defines._needUVs;
  34302. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  34303. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  34304. defines["TANGENT"] = true;
  34305. }
  34306. if (defines._needUVs) {
  34307. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  34308. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  34309. }
  34310. else {
  34311. defines["UV1"] = false;
  34312. defines["UV2"] = false;
  34313. }
  34314. if (useVertexColor) {
  34315. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  34316. defines["VERTEXCOLOR"] = hasVertexColors;
  34317. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  34318. }
  34319. if (useBones) {
  34320. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  34321. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  34322. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  34323. }
  34324. else {
  34325. defines["NUM_BONE_INFLUENCERS"] = 0;
  34326. defines["BonesPerMesh"] = 0;
  34327. }
  34328. }
  34329. if (useMorphTargets) {
  34330. var manager = mesh.morphTargetManager;
  34331. if (manager) {
  34332. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  34333. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  34334. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  34335. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  34336. }
  34337. else {
  34338. defines["MORPHTARGETS_TANGENT"] = false;
  34339. defines["MORPHTARGETS_NORMAL"] = false;
  34340. defines["MORPHTARGETS"] = false;
  34341. defines["NUM_MORPH_INFLUENCERS"] = 0;
  34342. }
  34343. }
  34344. return true;
  34345. };
  34346. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  34347. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34348. if (disableLighting === void 0) { disableLighting = false; }
  34349. if (!defines._areLightsDirty) {
  34350. return defines._needNormals;
  34351. }
  34352. var lightIndex = 0;
  34353. var needNormals = false;
  34354. var needRebuild = false;
  34355. var lightmapMode = false;
  34356. var shadowEnabled = false;
  34357. var specularEnabled = false;
  34358. if (scene.lightsEnabled && !disableLighting) {
  34359. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  34360. var light = _a[_i];
  34361. needNormals = true;
  34362. if (defines["LIGHT" + lightIndex] === undefined) {
  34363. needRebuild = true;
  34364. }
  34365. defines["LIGHT" + lightIndex] = true;
  34366. defines["SPOTLIGHT" + lightIndex] = false;
  34367. defines["HEMILIGHT" + lightIndex] = false;
  34368. defines["POINTLIGHT" + lightIndex] = false;
  34369. defines["DIRLIGHT" + lightIndex] = false;
  34370. var type;
  34371. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  34372. type = "SPOTLIGHT" + lightIndex;
  34373. }
  34374. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  34375. type = "HEMILIGHT" + lightIndex;
  34376. }
  34377. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  34378. type = "POINTLIGHT" + lightIndex;
  34379. }
  34380. else {
  34381. type = "DIRLIGHT" + lightIndex;
  34382. }
  34383. defines[type] = true;
  34384. // Specular
  34385. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  34386. specularEnabled = true;
  34387. }
  34388. // Shadows
  34389. defines["SHADOW" + lightIndex] = false;
  34390. defines["SHADOWPCF" + lightIndex] = false;
  34391. defines["SHADOWESM" + lightIndex] = false;
  34392. defines["SHADOWCUBE" + lightIndex] = false;
  34393. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  34394. var shadowGenerator = light.getShadowGenerator();
  34395. if (shadowGenerator) {
  34396. shadowEnabled = true;
  34397. shadowGenerator.prepareDefines(defines, lightIndex);
  34398. }
  34399. }
  34400. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  34401. lightmapMode = true;
  34402. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  34403. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  34404. }
  34405. else {
  34406. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  34407. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  34408. }
  34409. lightIndex++;
  34410. if (lightIndex === maxSimultaneousLights)
  34411. break;
  34412. }
  34413. }
  34414. defines["SPECULARTERM"] = specularEnabled;
  34415. defines["SHADOWS"] = shadowEnabled;
  34416. // Resetting all other lights if any
  34417. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  34418. if (defines["LIGHT" + index] !== undefined) {
  34419. defines["LIGHT" + index] = false;
  34420. defines["HEMILIGHT" + lightIndex] = false;
  34421. defines["POINTLIGHT" + lightIndex] = false;
  34422. defines["DIRLIGHT" + lightIndex] = false;
  34423. defines["SPOTLIGHT" + lightIndex] = false;
  34424. defines["SHADOW" + lightIndex] = false;
  34425. }
  34426. }
  34427. var caps = scene.getEngine().getCaps();
  34428. if (defines["SHADOWFLOAT"] === undefined) {
  34429. needRebuild = true;
  34430. }
  34431. defines["SHADOWFLOAT"] = shadowEnabled &&
  34432. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  34433. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  34434. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  34435. if (needRebuild) {
  34436. defines.rebuild();
  34437. }
  34438. return needNormals;
  34439. };
  34440. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  34441. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34442. var uniformsList;
  34443. var uniformBuffersList = null;
  34444. if (uniformsListOrOptions.uniformsNames) {
  34445. var options = uniformsListOrOptions;
  34446. uniformsList = options.uniformsNames;
  34447. uniformBuffersList = options.uniformBuffersNames;
  34448. samplersList = options.samplers;
  34449. defines = options.defines;
  34450. maxSimultaneousLights = options.maxSimultaneousLights;
  34451. }
  34452. else {
  34453. uniformsList = uniformsListOrOptions;
  34454. if (!samplersList) {
  34455. samplersList = [];
  34456. }
  34457. }
  34458. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  34459. if (!defines["LIGHT" + lightIndex]) {
  34460. break;
  34461. }
  34462. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  34463. if (uniformBuffersList) {
  34464. uniformBuffersList.push("Light" + lightIndex);
  34465. }
  34466. samplersList.push("shadowSampler" + lightIndex);
  34467. }
  34468. if (defines["NUM_MORPH_INFLUENCERS"]) {
  34469. uniformsList.push("morphTargetInfluences");
  34470. }
  34471. };
  34472. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  34473. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34474. if (rank === void 0) { rank = 0; }
  34475. var lightFallbackRank = 0;
  34476. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  34477. if (!defines["LIGHT" + lightIndex]) {
  34478. break;
  34479. }
  34480. if (lightIndex > 0) {
  34481. lightFallbackRank = rank + lightIndex;
  34482. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  34483. }
  34484. if (!defines["SHADOWS"]) {
  34485. if (defines["SHADOW" + lightIndex]) {
  34486. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  34487. }
  34488. if (defines["SHADOWPCF" + lightIndex]) {
  34489. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  34490. }
  34491. if (defines["SHADOWESM" + lightIndex]) {
  34492. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  34493. }
  34494. }
  34495. }
  34496. return lightFallbackRank++;
  34497. };
  34498. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  34499. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  34500. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  34501. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  34502. var manager = mesh.morphTargetManager;
  34503. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  34504. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  34505. for (var index = 0; index < influencers; index++) {
  34506. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  34507. if (normal) {
  34508. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  34509. }
  34510. if (tangent) {
  34511. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  34512. }
  34513. if (attribs.length > maxAttributesCount) {
  34514. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  34515. }
  34516. }
  34517. }
  34518. };
  34519. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  34520. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  34521. fallbacks.addCPUSkinningFallback(0, mesh);
  34522. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34523. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34524. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  34525. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  34526. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  34527. }
  34528. }
  34529. };
  34530. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  34531. if (defines["INSTANCES"]) {
  34532. attribs.push("world0");
  34533. attribs.push("world1");
  34534. attribs.push("world2");
  34535. attribs.push("world3");
  34536. }
  34537. };
  34538. // Bindings
  34539. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  34540. if (light.shadowEnabled && mesh.receiveShadows) {
  34541. var shadowGenerator = light.getShadowGenerator();
  34542. if (shadowGenerator) {
  34543. shadowGenerator.bindShadowLight(lightIndex, effect);
  34544. }
  34545. }
  34546. };
  34547. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  34548. light.transferToEffect(effect, lightIndex + "");
  34549. };
  34550. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  34551. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34552. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  34553. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  34554. for (var i = 0; i < len; i++) {
  34555. var light = mesh._lightSources[i];
  34556. var iAsString = i.toString();
  34557. var scaledIntensity = light.getScaledIntensity();
  34558. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  34559. MaterialHelper.BindLightProperties(light, effect, i);
  34560. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  34561. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  34562. if (defines["SPECULARTERM"]) {
  34563. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  34564. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  34565. }
  34566. // Shadows
  34567. if (scene.shadowsEnabled) {
  34568. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  34569. }
  34570. light._uniformBuffer.update();
  34571. }
  34572. };
  34573. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  34574. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  34575. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  34576. effect.setColor3("vFogColor", scene.fogColor);
  34577. }
  34578. };
  34579. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  34580. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  34581. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  34582. if (matrices && effect) {
  34583. effect.setMatrices("mBones", matrices);
  34584. }
  34585. }
  34586. };
  34587. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  34588. var manager = abstractMesh.morphTargetManager;
  34589. if (!abstractMesh || !manager) {
  34590. return;
  34591. }
  34592. effect.setFloatArray("morphTargetInfluences", manager.influences);
  34593. };
  34594. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  34595. if (defines["LOGARITHMICDEPTH"]) {
  34596. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  34597. }
  34598. };
  34599. MaterialHelper.BindClipPlane = function (effect, scene) {
  34600. if (scene.clipPlane) {
  34601. var clipPlane = scene.clipPlane;
  34602. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  34603. }
  34604. };
  34605. return MaterialHelper;
  34606. }());
  34607. BABYLON.MaterialHelper = MaterialHelper;
  34608. })(BABYLON || (BABYLON = {}));
  34609. //# sourceMappingURL=babylon.materialHelper.js.map
  34610. var BABYLON;
  34611. (function (BABYLON) {
  34612. var PushMaterial = /** @class */ (function (_super) {
  34613. __extends(PushMaterial, _super);
  34614. function PushMaterial(name, scene) {
  34615. var _this = _super.call(this, name, scene) || this;
  34616. _this.storeEffectOnSubMeshes = true;
  34617. return _this;
  34618. }
  34619. PushMaterial.prototype.getEffect = function () {
  34620. return this._activeEffect;
  34621. };
  34622. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  34623. if (!mesh) {
  34624. return false;
  34625. }
  34626. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  34627. return true;
  34628. }
  34629. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  34630. };
  34631. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  34632. this._activeEffect.setMatrix("world", world);
  34633. };
  34634. PushMaterial.prototype.bind = function (world, mesh) {
  34635. if (!mesh) {
  34636. return;
  34637. }
  34638. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  34639. };
  34640. PushMaterial.prototype._afterBind = function (mesh, effect) {
  34641. if (effect === void 0) { effect = null; }
  34642. _super.prototype._afterBind.call(this, mesh);
  34643. this.getScene()._cachedEffect = effect;
  34644. };
  34645. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  34646. if (visibility === void 0) { visibility = 1; }
  34647. return scene.isCachedMaterialInvalid(this, effect, visibility);
  34648. };
  34649. return PushMaterial;
  34650. }(BABYLON.Material));
  34651. BABYLON.PushMaterial = PushMaterial;
  34652. })(BABYLON || (BABYLON = {}));
  34653. //# sourceMappingURL=babylon.pushMaterial.js.map
  34654. var BABYLON;
  34655. (function (BABYLON) {
  34656. var StandardMaterialDefines = /** @class */ (function (_super) {
  34657. __extends(StandardMaterialDefines, _super);
  34658. function StandardMaterialDefines() {
  34659. var _this = _super.call(this) || this;
  34660. _this.MAINUV1 = false;
  34661. _this.MAINUV2 = false;
  34662. _this.DIFFUSE = false;
  34663. _this.DIFFUSEDIRECTUV = 0;
  34664. _this.AMBIENT = false;
  34665. _this.AMBIENTDIRECTUV = 0;
  34666. _this.OPACITY = false;
  34667. _this.OPACITYDIRECTUV = 0;
  34668. _this.OPACITYRGB = false;
  34669. _this.REFLECTION = false;
  34670. _this.EMISSIVE = false;
  34671. _this.EMISSIVEDIRECTUV = 0;
  34672. _this.SPECULAR = false;
  34673. _this.SPECULARDIRECTUV = 0;
  34674. _this.BUMP = false;
  34675. _this.BUMPDIRECTUV = 0;
  34676. _this.PARALLAX = false;
  34677. _this.PARALLAXOCCLUSION = false;
  34678. _this.SPECULAROVERALPHA = false;
  34679. _this.CLIPPLANE = false;
  34680. _this.ALPHATEST = false;
  34681. _this.DEPTHPREPASS = false;
  34682. _this.ALPHAFROMDIFFUSE = false;
  34683. _this.POINTSIZE = false;
  34684. _this.FOG = false;
  34685. _this.SPECULARTERM = false;
  34686. _this.DIFFUSEFRESNEL = false;
  34687. _this.OPACITYFRESNEL = false;
  34688. _this.REFLECTIONFRESNEL = false;
  34689. _this.REFRACTIONFRESNEL = false;
  34690. _this.EMISSIVEFRESNEL = false;
  34691. _this.FRESNEL = false;
  34692. _this.NORMAL = false;
  34693. _this.UV1 = false;
  34694. _this.UV2 = false;
  34695. _this.VERTEXCOLOR = false;
  34696. _this.VERTEXALPHA = false;
  34697. _this.NUM_BONE_INFLUENCERS = 0;
  34698. _this.BonesPerMesh = 0;
  34699. _this.INSTANCES = false;
  34700. _this.GLOSSINESS = false;
  34701. _this.ROUGHNESS = false;
  34702. _this.EMISSIVEASILLUMINATION = false;
  34703. _this.LINKEMISSIVEWITHDIFFUSE = false;
  34704. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  34705. _this.LIGHTMAP = false;
  34706. _this.LIGHTMAPDIRECTUV = 0;
  34707. _this.USELIGHTMAPASSHADOWMAP = false;
  34708. _this.REFLECTIONMAP_3D = false;
  34709. _this.REFLECTIONMAP_SPHERICAL = false;
  34710. _this.REFLECTIONMAP_PLANAR = false;
  34711. _this.REFLECTIONMAP_CUBIC = false;
  34712. _this.REFLECTIONMAP_PROJECTION = false;
  34713. _this.REFLECTIONMAP_SKYBOX = false;
  34714. _this.REFLECTIONMAP_EXPLICIT = false;
  34715. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  34716. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  34717. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  34718. _this.INVERTCUBICMAP = false;
  34719. _this.LOGARITHMICDEPTH = false;
  34720. _this.REFRACTION = false;
  34721. _this.REFRACTIONMAP_3D = false;
  34722. _this.REFLECTIONOVERALPHA = false;
  34723. _this.TWOSIDEDLIGHTING = false;
  34724. _this.SHADOWFLOAT = false;
  34725. _this.MORPHTARGETS = false;
  34726. _this.MORPHTARGETS_NORMAL = false;
  34727. _this.MORPHTARGETS_TANGENT = false;
  34728. _this.NUM_MORPH_INFLUENCERS = 0;
  34729. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  34730. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  34731. _this.IMAGEPROCESSING = false;
  34732. _this.VIGNETTE = false;
  34733. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  34734. _this.VIGNETTEBLENDMODEOPAQUE = false;
  34735. _this.TONEMAPPING = false;
  34736. _this.CONTRAST = false;
  34737. _this.COLORCURVES = false;
  34738. _this.COLORGRADING = false;
  34739. _this.COLORGRADING3D = false;
  34740. _this.SAMPLER3DGREENDEPTH = false;
  34741. _this.SAMPLER3DBGRMAP = false;
  34742. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  34743. _this.EXPOSURE = false;
  34744. _this.rebuild();
  34745. return _this;
  34746. }
  34747. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  34748. var modes = [
  34749. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  34750. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  34751. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  34752. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  34753. ];
  34754. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  34755. var mode = modes_1[_i];
  34756. this[mode] = (mode === modeToEnable);
  34757. }
  34758. };
  34759. return StandardMaterialDefines;
  34760. }(BABYLON.MaterialDefines));
  34761. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  34762. var StandardMaterial = /** @class */ (function (_super) {
  34763. __extends(StandardMaterial, _super);
  34764. function StandardMaterial(name, scene) {
  34765. var _this = _super.call(this, name, scene) || this;
  34766. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  34767. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  34768. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  34769. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  34770. _this.specularPower = 64;
  34771. _this._useAlphaFromDiffuseTexture = false;
  34772. _this._useEmissiveAsIllumination = false;
  34773. _this._linkEmissiveWithDiffuse = false;
  34774. _this._useSpecularOverAlpha = false;
  34775. _this._useReflectionOverAlpha = false;
  34776. _this._disableLighting = false;
  34777. _this._useParallax = false;
  34778. _this._useParallaxOcclusion = false;
  34779. _this.parallaxScaleBias = 0.05;
  34780. _this._roughness = 0;
  34781. _this.indexOfRefraction = 0.98;
  34782. _this.invertRefractionY = true;
  34783. _this._useLightmapAsShadowmap = false;
  34784. _this._useReflectionFresnelFromSpecular = false;
  34785. _this._useGlossinessFromSpecularMapAlpha = false;
  34786. _this._maxSimultaneousLights = 4;
  34787. /**
  34788. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  34789. */
  34790. _this._invertNormalMapX = false;
  34791. /**
  34792. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  34793. */
  34794. _this._invertNormalMapY = false;
  34795. /**
  34796. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  34797. */
  34798. _this._twoSidedLighting = false;
  34799. _this._renderTargets = new BABYLON.SmartArray(16);
  34800. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  34801. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  34802. // Setup the default processing configuration to the scene.
  34803. _this._attachImageProcessingConfiguration(null);
  34804. _this.getRenderTargetTextures = function () {
  34805. _this._renderTargets.reset();
  34806. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  34807. _this._renderTargets.push(_this._reflectionTexture);
  34808. }
  34809. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  34810. _this._renderTargets.push(_this._refractionTexture);
  34811. }
  34812. return _this._renderTargets;
  34813. };
  34814. return _this;
  34815. }
  34816. ;
  34817. ;
  34818. ;
  34819. ;
  34820. ;
  34821. ;
  34822. ;
  34823. ;
  34824. ;
  34825. ;
  34826. ;
  34827. ;
  34828. ;
  34829. ;
  34830. ;
  34831. ;
  34832. ;
  34833. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  34834. /**
  34835. * Gets the image processing configuration used either in this material.
  34836. */
  34837. get: function () {
  34838. return this._imageProcessingConfiguration;
  34839. },
  34840. /**
  34841. * Sets the Default image processing configuration used either in the this material.
  34842. *
  34843. * If sets to null, the scene one is in use.
  34844. */
  34845. set: function (value) {
  34846. this._attachImageProcessingConfiguration(value);
  34847. // Ensure the effect will be rebuilt.
  34848. this._markAllSubMeshesAsTexturesDirty();
  34849. },
  34850. enumerable: true,
  34851. configurable: true
  34852. });
  34853. /**
  34854. * Attaches a new image processing configuration to the Standard Material.
  34855. * @param configuration
  34856. */
  34857. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  34858. var _this = this;
  34859. if (configuration === this._imageProcessingConfiguration) {
  34860. return;
  34861. }
  34862. // Detaches observer.
  34863. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  34864. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  34865. }
  34866. // Pick the scene configuration if needed.
  34867. if (!configuration) {
  34868. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  34869. }
  34870. else {
  34871. this._imageProcessingConfiguration = configuration;
  34872. }
  34873. // Attaches observer.
  34874. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  34875. _this._markAllSubMeshesAsImageProcessingDirty();
  34876. });
  34877. };
  34878. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  34879. /**
  34880. * Gets wether the color curves effect is enabled.
  34881. */
  34882. get: function () {
  34883. return this.imageProcessingConfiguration.colorCurvesEnabled;
  34884. },
  34885. /**
  34886. * Sets wether the color curves effect is enabled.
  34887. */
  34888. set: function (value) {
  34889. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  34890. },
  34891. enumerable: true,
  34892. configurable: true
  34893. });
  34894. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  34895. /**
  34896. * Gets wether the color grading effect is enabled.
  34897. */
  34898. get: function () {
  34899. return this.imageProcessingConfiguration.colorGradingEnabled;
  34900. },
  34901. /**
  34902. * Gets wether the color grading effect is enabled.
  34903. */
  34904. set: function (value) {
  34905. this.imageProcessingConfiguration.colorGradingEnabled = value;
  34906. },
  34907. enumerable: true,
  34908. configurable: true
  34909. });
  34910. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  34911. /**
  34912. * Gets wether tonemapping is enabled or not.
  34913. */
  34914. get: function () {
  34915. return this._imageProcessingConfiguration.toneMappingEnabled;
  34916. },
  34917. /**
  34918. * Sets wether tonemapping is enabled or not
  34919. */
  34920. set: function (value) {
  34921. this._imageProcessingConfiguration.toneMappingEnabled = value;
  34922. },
  34923. enumerable: true,
  34924. configurable: true
  34925. });
  34926. ;
  34927. ;
  34928. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  34929. /**
  34930. * The camera exposure used on this material.
  34931. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  34932. * This corresponds to a photographic exposure.
  34933. */
  34934. get: function () {
  34935. return this._imageProcessingConfiguration.exposure;
  34936. },
  34937. /**
  34938. * The camera exposure used on this material.
  34939. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  34940. * This corresponds to a photographic exposure.
  34941. */
  34942. set: function (value) {
  34943. this._imageProcessingConfiguration.exposure = value;
  34944. },
  34945. enumerable: true,
  34946. configurable: true
  34947. });
  34948. ;
  34949. ;
  34950. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  34951. /**
  34952. * Gets The camera contrast used on this material.
  34953. */
  34954. get: function () {
  34955. return this._imageProcessingConfiguration.contrast;
  34956. },
  34957. /**
  34958. * Sets The camera contrast used on this material.
  34959. */
  34960. set: function (value) {
  34961. this._imageProcessingConfiguration.contrast = value;
  34962. },
  34963. enumerable: true,
  34964. configurable: true
  34965. });
  34966. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  34967. /**
  34968. * Gets the Color Grading 2D Lookup Texture.
  34969. */
  34970. get: function () {
  34971. return this._imageProcessingConfiguration.colorGradingTexture;
  34972. },
  34973. /**
  34974. * Sets the Color Grading 2D Lookup Texture.
  34975. */
  34976. set: function (value) {
  34977. this._imageProcessingConfiguration.colorGradingTexture = value;
  34978. },
  34979. enumerable: true,
  34980. configurable: true
  34981. });
  34982. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  34983. /**
  34984. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  34985. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  34986. * 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;
  34987. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  34988. */
  34989. get: function () {
  34990. return this._imageProcessingConfiguration.colorCurves;
  34991. },
  34992. /**
  34993. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  34994. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  34995. * 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;
  34996. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  34997. */
  34998. set: function (value) {
  34999. this._imageProcessingConfiguration.colorCurves = value;
  35000. },
  35001. enumerable: true,
  35002. configurable: true
  35003. });
  35004. StandardMaterial.prototype.getClassName = function () {
  35005. return "StandardMaterial";
  35006. };
  35007. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  35008. get: function () {
  35009. return this._useLogarithmicDepth;
  35010. },
  35011. set: function (value) {
  35012. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  35013. this._markAllSubMeshesAsMiscDirty();
  35014. },
  35015. enumerable: true,
  35016. configurable: true
  35017. });
  35018. StandardMaterial.prototype.needAlphaBlending = function () {
  35019. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  35020. };
  35021. StandardMaterial.prototype.needAlphaTesting = function () {
  35022. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  35023. };
  35024. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  35025. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  35026. };
  35027. StandardMaterial.prototype.getAlphaTestTexture = function () {
  35028. return this._diffuseTexture;
  35029. };
  35030. /**
  35031. * Child classes can use it to update shaders
  35032. */
  35033. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35034. if (useInstances === void 0) { useInstances = false; }
  35035. if (subMesh.effect && this.isFrozen) {
  35036. if (this._wasPreviouslyReady && subMesh.effect) {
  35037. return true;
  35038. }
  35039. }
  35040. if (!subMesh._materialDefines) {
  35041. subMesh._materialDefines = new StandardMaterialDefines();
  35042. }
  35043. var scene = this.getScene();
  35044. var defines = subMesh._materialDefines;
  35045. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  35046. if (defines._renderId === scene.getRenderId()) {
  35047. return true;
  35048. }
  35049. }
  35050. var engine = scene.getEngine();
  35051. // Lights
  35052. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  35053. // Textures
  35054. if (defines._areTexturesDirty) {
  35055. defines._needUVs = false;
  35056. defines.MAINUV1 = false;
  35057. defines.MAINUV2 = false;
  35058. if (scene.texturesEnabled) {
  35059. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35060. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  35061. return false;
  35062. }
  35063. else {
  35064. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  35065. }
  35066. }
  35067. else {
  35068. defines.DIFFUSE = false;
  35069. }
  35070. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35071. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  35072. return false;
  35073. }
  35074. else {
  35075. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  35076. }
  35077. }
  35078. else {
  35079. defines.AMBIENT = false;
  35080. }
  35081. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35082. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  35083. return false;
  35084. }
  35085. else {
  35086. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  35087. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  35088. }
  35089. }
  35090. else {
  35091. defines.OPACITY = false;
  35092. }
  35093. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35094. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  35095. return false;
  35096. }
  35097. else {
  35098. defines._needNormals = true;
  35099. defines.REFLECTION = true;
  35100. defines.ROUGHNESS = (this._roughness > 0);
  35101. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  35102. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  35103. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  35104. switch (this._reflectionTexture.coordinatesMode) {
  35105. case BABYLON.Texture.CUBIC_MODE:
  35106. case BABYLON.Texture.INVCUBIC_MODE:
  35107. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  35108. break;
  35109. case BABYLON.Texture.EXPLICIT_MODE:
  35110. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  35111. break;
  35112. case BABYLON.Texture.PLANAR_MODE:
  35113. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  35114. break;
  35115. case BABYLON.Texture.PROJECTION_MODE:
  35116. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  35117. break;
  35118. case BABYLON.Texture.SKYBOX_MODE:
  35119. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  35120. break;
  35121. case BABYLON.Texture.SPHERICAL_MODE:
  35122. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  35123. break;
  35124. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  35125. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  35126. break;
  35127. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  35128. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  35129. break;
  35130. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  35131. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  35132. break;
  35133. }
  35134. }
  35135. }
  35136. else {
  35137. defines.REFLECTION = false;
  35138. }
  35139. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35140. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  35141. return false;
  35142. }
  35143. else {
  35144. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  35145. }
  35146. }
  35147. else {
  35148. defines.EMISSIVE = false;
  35149. }
  35150. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35151. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  35152. return false;
  35153. }
  35154. else {
  35155. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  35156. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  35157. }
  35158. }
  35159. else {
  35160. defines.LIGHTMAP = false;
  35161. }
  35162. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35163. if (!this._specularTexture.isReadyOrNotBlocking()) {
  35164. return false;
  35165. }
  35166. else {
  35167. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  35168. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  35169. }
  35170. }
  35171. else {
  35172. defines.SPECULAR = false;
  35173. }
  35174. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  35175. // Bump texure can not be not blocking.
  35176. if (!this._bumpTexture.isReady()) {
  35177. return false;
  35178. }
  35179. else {
  35180. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  35181. defines.PARALLAX = this._useParallax;
  35182. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  35183. }
  35184. }
  35185. else {
  35186. defines.BUMP = false;
  35187. }
  35188. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35189. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  35190. return false;
  35191. }
  35192. else {
  35193. defines._needUVs = true;
  35194. defines.REFRACTION = true;
  35195. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  35196. }
  35197. }
  35198. else {
  35199. defines.REFRACTION = false;
  35200. }
  35201. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  35202. }
  35203. else {
  35204. defines.DIFFUSE = false;
  35205. defines.AMBIENT = false;
  35206. defines.OPACITY = false;
  35207. defines.REFLECTION = false;
  35208. defines.EMISSIVE = false;
  35209. defines.LIGHTMAP = false;
  35210. defines.BUMP = false;
  35211. defines.REFRACTION = false;
  35212. }
  35213. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  35214. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  35215. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  35216. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  35217. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  35218. }
  35219. if (defines._areImageProcessingDirty) {
  35220. if (!this._imageProcessingConfiguration.isReady()) {
  35221. return false;
  35222. }
  35223. this._imageProcessingConfiguration.prepareDefines(defines);
  35224. }
  35225. if (defines._areFresnelDirty) {
  35226. if (StandardMaterial.FresnelEnabled) {
  35227. // Fresnel
  35228. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  35229. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  35230. this._reflectionFresnelParameters) {
  35231. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  35232. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  35233. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  35234. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  35235. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  35236. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  35237. defines._needNormals = true;
  35238. defines.FRESNEL = true;
  35239. }
  35240. }
  35241. else {
  35242. defines.FRESNEL = false;
  35243. }
  35244. }
  35245. // Misc.
  35246. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  35247. // Attribs
  35248. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  35249. // Values that need to be evaluated on every frame
  35250. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  35251. // Get correct effect
  35252. if (defines.isDirty) {
  35253. defines.markAsProcessed();
  35254. scene.resetCachedMaterial();
  35255. // Fallbacks
  35256. var fallbacks = new BABYLON.EffectFallbacks();
  35257. if (defines.REFLECTION) {
  35258. fallbacks.addFallback(0, "REFLECTION");
  35259. }
  35260. if (defines.SPECULAR) {
  35261. fallbacks.addFallback(0, "SPECULAR");
  35262. }
  35263. if (defines.BUMP) {
  35264. fallbacks.addFallback(0, "BUMP");
  35265. }
  35266. if (defines.PARALLAX) {
  35267. fallbacks.addFallback(1, "PARALLAX");
  35268. }
  35269. if (defines.PARALLAXOCCLUSION) {
  35270. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  35271. }
  35272. if (defines.SPECULAROVERALPHA) {
  35273. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  35274. }
  35275. if (defines.FOG) {
  35276. fallbacks.addFallback(1, "FOG");
  35277. }
  35278. if (defines.POINTSIZE) {
  35279. fallbacks.addFallback(0, "POINTSIZE");
  35280. }
  35281. if (defines.LOGARITHMICDEPTH) {
  35282. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  35283. }
  35284. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  35285. if (defines.SPECULARTERM) {
  35286. fallbacks.addFallback(0, "SPECULARTERM");
  35287. }
  35288. if (defines.DIFFUSEFRESNEL) {
  35289. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  35290. }
  35291. if (defines.OPACITYFRESNEL) {
  35292. fallbacks.addFallback(2, "OPACITYFRESNEL");
  35293. }
  35294. if (defines.REFLECTIONFRESNEL) {
  35295. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  35296. }
  35297. if (defines.EMISSIVEFRESNEL) {
  35298. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  35299. }
  35300. if (defines.FRESNEL) {
  35301. fallbacks.addFallback(4, "FRESNEL");
  35302. }
  35303. //Attributes
  35304. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35305. if (defines.NORMAL) {
  35306. attribs.push(BABYLON.VertexBuffer.NormalKind);
  35307. }
  35308. if (defines.UV1) {
  35309. attribs.push(BABYLON.VertexBuffer.UVKind);
  35310. }
  35311. if (defines.UV2) {
  35312. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35313. }
  35314. if (defines.VERTEXCOLOR) {
  35315. attribs.push(BABYLON.VertexBuffer.ColorKind);
  35316. }
  35317. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  35318. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  35319. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  35320. var shaderName = "default";
  35321. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  35322. "vFogInfos", "vFogColor", "pointSize",
  35323. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  35324. "mBones",
  35325. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  35326. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  35327. "logarithmicDepthConstant", "vTangentSpaceParams"
  35328. ];
  35329. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  35330. var uniformBuffers = ["Material", "Scene"];
  35331. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  35332. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  35333. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  35334. uniformsNames: uniforms,
  35335. uniformBuffersNames: uniformBuffers,
  35336. samplers: samplers,
  35337. defines: defines,
  35338. maxSimultaneousLights: this._maxSimultaneousLights
  35339. });
  35340. if (this.customShaderNameResolve) {
  35341. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  35342. }
  35343. var join = defines.toString();
  35344. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  35345. attributes: attribs,
  35346. uniformsNames: uniforms,
  35347. uniformBuffersNames: uniformBuffers,
  35348. samplers: samplers,
  35349. defines: join,
  35350. fallbacks: fallbacks,
  35351. onCompiled: this.onCompiled,
  35352. onError: this.onError,
  35353. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  35354. }, engine), defines);
  35355. this.buildUniformLayout();
  35356. }
  35357. if (!subMesh.effect || !subMesh.effect.isReady()) {
  35358. return false;
  35359. }
  35360. defines._renderId = scene.getRenderId();
  35361. this._wasPreviouslyReady = true;
  35362. return true;
  35363. };
  35364. StandardMaterial.prototype.buildUniformLayout = function () {
  35365. // Order is important !
  35366. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  35367. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  35368. this._uniformBuffer.addUniform("opacityParts", 4);
  35369. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  35370. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  35371. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  35372. this._uniformBuffer.addUniform("refractionRightColor", 4);
  35373. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  35374. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  35375. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  35376. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  35377. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  35378. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  35379. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  35380. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  35381. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  35382. this._uniformBuffer.addUniform("vBumpInfos", 3);
  35383. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  35384. this._uniformBuffer.addUniform("ambientMatrix", 16);
  35385. this._uniformBuffer.addUniform("opacityMatrix", 16);
  35386. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  35387. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  35388. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  35389. this._uniformBuffer.addUniform("specularMatrix", 16);
  35390. this._uniformBuffer.addUniform("bumpMatrix", 16);
  35391. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  35392. this._uniformBuffer.addUniform("refractionMatrix", 16);
  35393. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  35394. this._uniformBuffer.addUniform("vSpecularColor", 4);
  35395. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  35396. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  35397. this._uniformBuffer.addUniform("pointSize", 1);
  35398. this._uniformBuffer.create();
  35399. };
  35400. StandardMaterial.prototype.unbind = function () {
  35401. if (this._activeEffect) {
  35402. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  35403. this._activeEffect.setTexture("reflection2DSampler", null);
  35404. }
  35405. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  35406. this._activeEffect.setTexture("refraction2DSampler", null);
  35407. }
  35408. }
  35409. _super.prototype.unbind.call(this);
  35410. };
  35411. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35412. var scene = this.getScene();
  35413. var defines = subMesh._materialDefines;
  35414. if (!defines) {
  35415. return;
  35416. }
  35417. var effect = subMesh.effect;
  35418. if (!effect) {
  35419. return;
  35420. }
  35421. this._activeEffect = effect;
  35422. // Matrices
  35423. this.bindOnlyWorldMatrix(world);
  35424. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  35425. // Bones
  35426. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  35427. if (mustRebind) {
  35428. this._uniformBuffer.bindToEffect(effect, "Material");
  35429. this.bindViewProjection(effect);
  35430. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  35431. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  35432. // Fresnel
  35433. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  35434. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  35435. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  35436. }
  35437. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  35438. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  35439. }
  35440. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  35441. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  35442. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  35443. }
  35444. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  35445. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  35446. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  35447. }
  35448. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  35449. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  35450. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  35451. }
  35452. }
  35453. // Textures
  35454. if (scene.texturesEnabled) {
  35455. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35456. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  35457. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  35458. }
  35459. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35460. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  35461. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  35462. }
  35463. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35464. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  35465. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  35466. }
  35467. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35468. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  35469. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  35470. }
  35471. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35472. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  35473. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  35474. }
  35475. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35476. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  35477. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  35478. }
  35479. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35480. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  35481. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  35482. }
  35483. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  35484. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  35485. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  35486. if (scene._mirroredCameraPosition) {
  35487. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  35488. }
  35489. else {
  35490. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  35491. }
  35492. }
  35493. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35494. var depth = 1.0;
  35495. if (!this._refractionTexture.isCube) {
  35496. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  35497. if (this._refractionTexture.depth) {
  35498. depth = this._refractionTexture.depth;
  35499. }
  35500. }
  35501. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  35502. }
  35503. }
  35504. // Point size
  35505. if (this.pointsCloud) {
  35506. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  35507. }
  35508. if (defines.SPECULARTERM) {
  35509. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  35510. }
  35511. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  35512. // Diffuse
  35513. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  35514. }
  35515. // Textures
  35516. if (scene.texturesEnabled) {
  35517. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35518. effect.setTexture("diffuseSampler", this._diffuseTexture);
  35519. }
  35520. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35521. effect.setTexture("ambientSampler", this._ambientTexture);
  35522. }
  35523. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35524. effect.setTexture("opacitySampler", this._opacityTexture);
  35525. }
  35526. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35527. if (this._reflectionTexture.isCube) {
  35528. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  35529. }
  35530. else {
  35531. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  35532. }
  35533. }
  35534. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35535. effect.setTexture("emissiveSampler", this._emissiveTexture);
  35536. }
  35537. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35538. effect.setTexture("lightmapSampler", this._lightmapTexture);
  35539. }
  35540. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35541. effect.setTexture("specularSampler", this._specularTexture);
  35542. }
  35543. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  35544. effect.setTexture("bumpSampler", this._bumpTexture);
  35545. }
  35546. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35547. var depth = 1.0;
  35548. if (this._refractionTexture.isCube) {
  35549. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  35550. }
  35551. else {
  35552. effect.setTexture("refraction2DSampler", this._refractionTexture);
  35553. }
  35554. }
  35555. }
  35556. // Clip plane
  35557. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  35558. // Colors
  35559. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  35560. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  35561. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  35562. }
  35563. if (mustRebind || !this.isFrozen) {
  35564. // Lights
  35565. if (scene.lightsEnabled && !this._disableLighting) {
  35566. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  35567. }
  35568. // View
  35569. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  35570. this.bindView(effect);
  35571. }
  35572. // Fog
  35573. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  35574. // Morph targets
  35575. if (defines.NUM_MORPH_INFLUENCERS) {
  35576. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  35577. }
  35578. // Log. depth
  35579. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  35580. // image processing
  35581. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  35582. this._imageProcessingConfiguration.bind(this._activeEffect);
  35583. }
  35584. }
  35585. this._uniformBuffer.update();
  35586. this._afterBind(mesh, this._activeEffect);
  35587. };
  35588. StandardMaterial.prototype.getAnimatables = function () {
  35589. var results = [];
  35590. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  35591. results.push(this._diffuseTexture);
  35592. }
  35593. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  35594. results.push(this._ambientTexture);
  35595. }
  35596. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  35597. results.push(this._opacityTexture);
  35598. }
  35599. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  35600. results.push(this._reflectionTexture);
  35601. }
  35602. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  35603. results.push(this._emissiveTexture);
  35604. }
  35605. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  35606. results.push(this._specularTexture);
  35607. }
  35608. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  35609. results.push(this._bumpTexture);
  35610. }
  35611. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  35612. results.push(this._lightmapTexture);
  35613. }
  35614. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  35615. results.push(this._refractionTexture);
  35616. }
  35617. return results;
  35618. };
  35619. StandardMaterial.prototype.getActiveTextures = function () {
  35620. var activeTextures = _super.prototype.getActiveTextures.call(this);
  35621. if (this._diffuseTexture) {
  35622. activeTextures.push(this._diffuseTexture);
  35623. }
  35624. if (this._ambientTexture) {
  35625. activeTextures.push(this._ambientTexture);
  35626. }
  35627. if (this._opacityTexture) {
  35628. activeTextures.push(this._opacityTexture);
  35629. }
  35630. if (this._reflectionTexture) {
  35631. activeTextures.push(this._reflectionTexture);
  35632. }
  35633. if (this._emissiveTexture) {
  35634. activeTextures.push(this._emissiveTexture);
  35635. }
  35636. if (this._specularTexture) {
  35637. activeTextures.push(this._specularTexture);
  35638. }
  35639. if (this._bumpTexture) {
  35640. activeTextures.push(this._bumpTexture);
  35641. }
  35642. if (this._lightmapTexture) {
  35643. activeTextures.push(this._lightmapTexture);
  35644. }
  35645. if (this._refractionTexture) {
  35646. activeTextures.push(this._refractionTexture);
  35647. }
  35648. return activeTextures;
  35649. };
  35650. StandardMaterial.prototype.hasTexture = function (texture) {
  35651. if (_super.prototype.hasTexture.call(this, texture)) {
  35652. return true;
  35653. }
  35654. if (this._diffuseTexture === texture) {
  35655. return true;
  35656. }
  35657. if (this._ambientTexture === texture) {
  35658. return true;
  35659. }
  35660. if (this._opacityTexture === texture) {
  35661. return true;
  35662. }
  35663. if (this._reflectionTexture === texture) {
  35664. return true;
  35665. }
  35666. if (this._emissiveTexture === texture) {
  35667. return true;
  35668. }
  35669. if (this._specularTexture === texture) {
  35670. return true;
  35671. }
  35672. if (this._bumpTexture === texture) {
  35673. return true;
  35674. }
  35675. if (this._lightmapTexture === texture) {
  35676. return true;
  35677. }
  35678. if (this._refractionTexture === texture) {
  35679. return true;
  35680. }
  35681. return false;
  35682. };
  35683. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35684. if (forceDisposeTextures) {
  35685. if (this._diffuseTexture) {
  35686. this._diffuseTexture.dispose();
  35687. }
  35688. if (this._ambientTexture) {
  35689. this._ambientTexture.dispose();
  35690. }
  35691. if (this._opacityTexture) {
  35692. this._opacityTexture.dispose();
  35693. }
  35694. if (this._reflectionTexture) {
  35695. this._reflectionTexture.dispose();
  35696. }
  35697. if (this._emissiveTexture) {
  35698. this._emissiveTexture.dispose();
  35699. }
  35700. if (this._specularTexture) {
  35701. this._specularTexture.dispose();
  35702. }
  35703. if (this._bumpTexture) {
  35704. this._bumpTexture.dispose();
  35705. }
  35706. if (this._lightmapTexture) {
  35707. this._lightmapTexture.dispose();
  35708. }
  35709. if (this._refractionTexture) {
  35710. this._refractionTexture.dispose();
  35711. }
  35712. }
  35713. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35714. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35715. }
  35716. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  35717. };
  35718. StandardMaterial.prototype.clone = function (name) {
  35719. var _this = this;
  35720. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  35721. result.name = name;
  35722. result.id = name;
  35723. return result;
  35724. };
  35725. StandardMaterial.prototype.serialize = function () {
  35726. return BABYLON.SerializationHelper.Serialize(this);
  35727. };
  35728. // Statics
  35729. StandardMaterial.Parse = function (source, scene, rootUrl) {
  35730. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  35731. };
  35732. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  35733. get: function () {
  35734. return StandardMaterial._DiffuseTextureEnabled;
  35735. },
  35736. set: function (value) {
  35737. if (StandardMaterial._DiffuseTextureEnabled === value) {
  35738. return;
  35739. }
  35740. StandardMaterial._DiffuseTextureEnabled = value;
  35741. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35742. },
  35743. enumerable: true,
  35744. configurable: true
  35745. });
  35746. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  35747. get: function () {
  35748. return StandardMaterial._AmbientTextureEnabled;
  35749. },
  35750. set: function (value) {
  35751. if (StandardMaterial._AmbientTextureEnabled === value) {
  35752. return;
  35753. }
  35754. StandardMaterial._AmbientTextureEnabled = value;
  35755. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35756. },
  35757. enumerable: true,
  35758. configurable: true
  35759. });
  35760. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  35761. get: function () {
  35762. return StandardMaterial._OpacityTextureEnabled;
  35763. },
  35764. set: function (value) {
  35765. if (StandardMaterial._OpacityTextureEnabled === value) {
  35766. return;
  35767. }
  35768. StandardMaterial._OpacityTextureEnabled = value;
  35769. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35770. },
  35771. enumerable: true,
  35772. configurable: true
  35773. });
  35774. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  35775. get: function () {
  35776. return StandardMaterial._ReflectionTextureEnabled;
  35777. },
  35778. set: function (value) {
  35779. if (StandardMaterial._ReflectionTextureEnabled === value) {
  35780. return;
  35781. }
  35782. StandardMaterial._ReflectionTextureEnabled = value;
  35783. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35784. },
  35785. enumerable: true,
  35786. configurable: true
  35787. });
  35788. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  35789. get: function () {
  35790. return StandardMaterial._EmissiveTextureEnabled;
  35791. },
  35792. set: function (value) {
  35793. if (StandardMaterial._EmissiveTextureEnabled === value) {
  35794. return;
  35795. }
  35796. StandardMaterial._EmissiveTextureEnabled = value;
  35797. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35798. },
  35799. enumerable: true,
  35800. configurable: true
  35801. });
  35802. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  35803. get: function () {
  35804. return StandardMaterial._SpecularTextureEnabled;
  35805. },
  35806. set: function (value) {
  35807. if (StandardMaterial._SpecularTextureEnabled === value) {
  35808. return;
  35809. }
  35810. StandardMaterial._SpecularTextureEnabled = value;
  35811. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35812. },
  35813. enumerable: true,
  35814. configurable: true
  35815. });
  35816. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  35817. get: function () {
  35818. return StandardMaterial._BumpTextureEnabled;
  35819. },
  35820. set: function (value) {
  35821. if (StandardMaterial._BumpTextureEnabled === value) {
  35822. return;
  35823. }
  35824. StandardMaterial._BumpTextureEnabled = value;
  35825. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35826. },
  35827. enumerable: true,
  35828. configurable: true
  35829. });
  35830. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  35831. get: function () {
  35832. return StandardMaterial._LightmapTextureEnabled;
  35833. },
  35834. set: function (value) {
  35835. if (StandardMaterial._LightmapTextureEnabled === value) {
  35836. return;
  35837. }
  35838. StandardMaterial._LightmapTextureEnabled = value;
  35839. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35840. },
  35841. enumerable: true,
  35842. configurable: true
  35843. });
  35844. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  35845. get: function () {
  35846. return StandardMaterial._RefractionTextureEnabled;
  35847. },
  35848. set: function (value) {
  35849. if (StandardMaterial._RefractionTextureEnabled === value) {
  35850. return;
  35851. }
  35852. StandardMaterial._RefractionTextureEnabled = value;
  35853. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35854. },
  35855. enumerable: true,
  35856. configurable: true
  35857. });
  35858. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  35859. get: function () {
  35860. return StandardMaterial._ColorGradingTextureEnabled;
  35861. },
  35862. set: function (value) {
  35863. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  35864. return;
  35865. }
  35866. StandardMaterial._ColorGradingTextureEnabled = value;
  35867. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35868. },
  35869. enumerable: true,
  35870. configurable: true
  35871. });
  35872. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  35873. get: function () {
  35874. return StandardMaterial._FresnelEnabled;
  35875. },
  35876. set: function (value) {
  35877. if (StandardMaterial._FresnelEnabled === value) {
  35878. return;
  35879. }
  35880. StandardMaterial._FresnelEnabled = value;
  35881. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  35882. },
  35883. enumerable: true,
  35884. configurable: true
  35885. });
  35886. // Flags used to enable or disable a type of texture for all Standard Materials
  35887. StandardMaterial._DiffuseTextureEnabled = true;
  35888. StandardMaterial._AmbientTextureEnabled = true;
  35889. StandardMaterial._OpacityTextureEnabled = true;
  35890. StandardMaterial._ReflectionTextureEnabled = true;
  35891. StandardMaterial._EmissiveTextureEnabled = true;
  35892. StandardMaterial._SpecularTextureEnabled = true;
  35893. StandardMaterial._BumpTextureEnabled = true;
  35894. StandardMaterial._LightmapTextureEnabled = true;
  35895. StandardMaterial._RefractionTextureEnabled = true;
  35896. StandardMaterial._ColorGradingTextureEnabled = true;
  35897. StandardMaterial._FresnelEnabled = true;
  35898. __decorate([
  35899. BABYLON.serializeAsTexture("diffuseTexture")
  35900. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  35901. __decorate([
  35902. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35903. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  35904. __decorate([
  35905. BABYLON.serializeAsTexture("ambientTexture")
  35906. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  35907. __decorate([
  35908. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35909. ], StandardMaterial.prototype, "ambientTexture", void 0);
  35910. __decorate([
  35911. BABYLON.serializeAsTexture("opacityTexture")
  35912. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  35913. __decorate([
  35914. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35915. ], StandardMaterial.prototype, "opacityTexture", void 0);
  35916. __decorate([
  35917. BABYLON.serializeAsTexture("reflectionTexture")
  35918. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  35919. __decorate([
  35920. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35921. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  35922. __decorate([
  35923. BABYLON.serializeAsTexture("emissiveTexture")
  35924. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  35925. __decorate([
  35926. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35927. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  35928. __decorate([
  35929. BABYLON.serializeAsTexture("specularTexture")
  35930. ], StandardMaterial.prototype, "_specularTexture", void 0);
  35931. __decorate([
  35932. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35933. ], StandardMaterial.prototype, "specularTexture", void 0);
  35934. __decorate([
  35935. BABYLON.serializeAsTexture("bumpTexture")
  35936. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  35937. __decorate([
  35938. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35939. ], StandardMaterial.prototype, "bumpTexture", void 0);
  35940. __decorate([
  35941. BABYLON.serializeAsTexture("lightmapTexture")
  35942. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  35943. __decorate([
  35944. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35945. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  35946. __decorate([
  35947. BABYLON.serializeAsTexture("refractionTexture")
  35948. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  35949. __decorate([
  35950. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35951. ], StandardMaterial.prototype, "refractionTexture", void 0);
  35952. __decorate([
  35953. BABYLON.serializeAsColor3("ambient")
  35954. ], StandardMaterial.prototype, "ambientColor", void 0);
  35955. __decorate([
  35956. BABYLON.serializeAsColor3("diffuse")
  35957. ], StandardMaterial.prototype, "diffuseColor", void 0);
  35958. __decorate([
  35959. BABYLON.serializeAsColor3("specular")
  35960. ], StandardMaterial.prototype, "specularColor", void 0);
  35961. __decorate([
  35962. BABYLON.serializeAsColor3("emissive")
  35963. ], StandardMaterial.prototype, "emissiveColor", void 0);
  35964. __decorate([
  35965. BABYLON.serialize()
  35966. ], StandardMaterial.prototype, "specularPower", void 0);
  35967. __decorate([
  35968. BABYLON.serialize("useAlphaFromDiffuseTexture")
  35969. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  35970. __decorate([
  35971. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35972. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  35973. __decorate([
  35974. BABYLON.serialize("useEmissiveAsIllumination")
  35975. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  35976. __decorate([
  35977. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35978. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  35979. __decorate([
  35980. BABYLON.serialize("linkEmissiveWithDiffuse")
  35981. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  35982. __decorate([
  35983. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35984. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  35985. __decorate([
  35986. BABYLON.serialize("useSpecularOverAlpha")
  35987. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  35988. __decorate([
  35989. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35990. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  35991. __decorate([
  35992. BABYLON.serialize("useReflectionOverAlpha")
  35993. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  35994. __decorate([
  35995. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35996. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  35997. __decorate([
  35998. BABYLON.serialize("disableLighting")
  35999. ], StandardMaterial.prototype, "_disableLighting", void 0);
  36000. __decorate([
  36001. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36002. ], StandardMaterial.prototype, "disableLighting", void 0);
  36003. __decorate([
  36004. BABYLON.serialize("useParallax")
  36005. ], StandardMaterial.prototype, "_useParallax", void 0);
  36006. __decorate([
  36007. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36008. ], StandardMaterial.prototype, "useParallax", void 0);
  36009. __decorate([
  36010. BABYLON.serialize("useParallaxOcclusion")
  36011. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  36012. __decorate([
  36013. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36014. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  36015. __decorate([
  36016. BABYLON.serialize()
  36017. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  36018. __decorate([
  36019. BABYLON.serialize("roughness")
  36020. ], StandardMaterial.prototype, "_roughness", void 0);
  36021. __decorate([
  36022. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36023. ], StandardMaterial.prototype, "roughness", void 0);
  36024. __decorate([
  36025. BABYLON.serialize()
  36026. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  36027. __decorate([
  36028. BABYLON.serialize()
  36029. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  36030. __decorate([
  36031. BABYLON.serialize("useLightmapAsShadowmap")
  36032. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  36033. __decorate([
  36034. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36035. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  36036. __decorate([
  36037. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  36038. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  36039. __decorate([
  36040. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36041. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  36042. __decorate([
  36043. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  36044. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  36045. __decorate([
  36046. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36047. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  36048. __decorate([
  36049. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  36050. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  36051. __decorate([
  36052. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36053. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  36054. __decorate([
  36055. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  36056. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  36057. __decorate([
  36058. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36059. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  36060. __decorate([
  36061. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  36062. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  36063. __decorate([
  36064. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36065. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  36066. __decorate([
  36067. BABYLON.serialize("useReflectionFresnelFromSpecular")
  36068. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  36069. __decorate([
  36070. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36071. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  36072. __decorate([
  36073. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  36074. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  36075. __decorate([
  36076. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36077. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  36078. __decorate([
  36079. BABYLON.serialize("maxSimultaneousLights")
  36080. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  36081. __decorate([
  36082. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36083. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  36084. __decorate([
  36085. BABYLON.serialize("invertNormalMapX")
  36086. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  36087. __decorate([
  36088. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36089. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  36090. __decorate([
  36091. BABYLON.serialize("invertNormalMapY")
  36092. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  36093. __decorate([
  36094. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36095. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  36096. __decorate([
  36097. BABYLON.serialize("twoSidedLighting")
  36098. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  36099. __decorate([
  36100. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36101. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  36102. __decorate([
  36103. BABYLON.serialize()
  36104. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  36105. return StandardMaterial;
  36106. }(BABYLON.PushMaterial));
  36107. BABYLON.StandardMaterial = StandardMaterial;
  36108. })(BABYLON || (BABYLON = {}));
  36109. //# sourceMappingURL=babylon.standardMaterial.js.map
  36110. var BABYLON;
  36111. (function (BABYLON) {
  36112. var PBRMaterialDefines = /** @class */ (function (_super) {
  36113. __extends(PBRMaterialDefines, _super);
  36114. function PBRMaterialDefines() {
  36115. var _this = _super.call(this) || this;
  36116. _this.PBR = true;
  36117. _this.MAINUV1 = false;
  36118. _this.MAINUV2 = false;
  36119. _this.UV1 = false;
  36120. _this.UV2 = false;
  36121. _this.ALBEDO = false;
  36122. _this.ALBEDODIRECTUV = 0;
  36123. _this.VERTEXCOLOR = false;
  36124. _this.AMBIENT = false;
  36125. _this.AMBIENTDIRECTUV = 0;
  36126. _this.AMBIENTINGRAYSCALE = false;
  36127. _this.OPACITY = false;
  36128. _this.VERTEXALPHA = false;
  36129. _this.OPACITYDIRECTUV = 0;
  36130. _this.OPACITYRGB = false;
  36131. _this.ALPHATEST = false;
  36132. _this.DEPTHPREPASS = false;
  36133. _this.ALPHABLEND = false;
  36134. _this.ALPHAFROMALBEDO = false;
  36135. _this.ALPHATESTVALUE = 0.5;
  36136. _this.SPECULAROVERALPHA = false;
  36137. _this.RADIANCEOVERALPHA = false;
  36138. _this.ALPHAFRESNEL = false;
  36139. _this.LINEARALPHAFRESNEL = false;
  36140. _this.PREMULTIPLYALPHA = false;
  36141. _this.EMISSIVE = false;
  36142. _this.EMISSIVEDIRECTUV = 0;
  36143. _this.REFLECTIVITY = false;
  36144. _this.REFLECTIVITYDIRECTUV = 0;
  36145. _this.SPECULARTERM = false;
  36146. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  36147. _this.MICROSURFACEAUTOMATIC = false;
  36148. _this.LODBASEDMICROSFURACE = false;
  36149. _this.MICROSURFACEMAP = false;
  36150. _this.MICROSURFACEMAPDIRECTUV = 0;
  36151. _this.METALLICWORKFLOW = false;
  36152. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  36153. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  36154. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  36155. _this.AOSTOREINMETALMAPRED = false;
  36156. _this.ENVIRONMENTBRDF = false;
  36157. _this.NORMAL = false;
  36158. _this.TANGENT = false;
  36159. _this.BUMP = false;
  36160. _this.BUMPDIRECTUV = 0;
  36161. _this.PARALLAX = false;
  36162. _this.PARALLAXOCCLUSION = false;
  36163. _this.NORMALXYSCALE = true;
  36164. _this.LIGHTMAP = false;
  36165. _this.LIGHTMAPDIRECTUV = 0;
  36166. _this.USELIGHTMAPASSHADOWMAP = false;
  36167. _this.REFLECTION = false;
  36168. _this.REFLECTIONMAP_3D = false;
  36169. _this.REFLECTIONMAP_SPHERICAL = false;
  36170. _this.REFLECTIONMAP_PLANAR = false;
  36171. _this.REFLECTIONMAP_CUBIC = false;
  36172. _this.REFLECTIONMAP_PROJECTION = false;
  36173. _this.REFLECTIONMAP_SKYBOX = false;
  36174. _this.REFLECTIONMAP_EXPLICIT = false;
  36175. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  36176. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  36177. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  36178. _this.INVERTCUBICMAP = false;
  36179. _this.USESPHERICALFROMREFLECTIONMAP = false;
  36180. _this.USESPHERICALINVERTEX = false;
  36181. _this.REFLECTIONMAP_OPPOSITEZ = false;
  36182. _this.LODINREFLECTIONALPHA = false;
  36183. _this.GAMMAREFLECTION = false;
  36184. _this.RADIANCEOCCLUSION = false;
  36185. _this.HORIZONOCCLUSION = false;
  36186. _this.REFRACTION = false;
  36187. _this.REFRACTIONMAP_3D = false;
  36188. _this.REFRACTIONMAP_OPPOSITEZ = false;
  36189. _this.LODINREFRACTIONALPHA = false;
  36190. _this.GAMMAREFRACTION = false;
  36191. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  36192. _this.INSTANCES = false;
  36193. _this.NUM_BONE_INFLUENCERS = 0;
  36194. _this.BonesPerMesh = 0;
  36195. _this.NONUNIFORMSCALING = false;
  36196. _this.MORPHTARGETS = false;
  36197. _this.MORPHTARGETS_NORMAL = false;
  36198. _this.MORPHTARGETS_TANGENT = false;
  36199. _this.NUM_MORPH_INFLUENCERS = 0;
  36200. _this.IMAGEPROCESSING = false;
  36201. _this.VIGNETTE = false;
  36202. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  36203. _this.VIGNETTEBLENDMODEOPAQUE = false;
  36204. _this.TONEMAPPING = false;
  36205. _this.CONTRAST = false;
  36206. _this.COLORCURVES = false;
  36207. _this.COLORGRADING = false;
  36208. _this.COLORGRADING3D = false;
  36209. _this.SAMPLER3DGREENDEPTH = false;
  36210. _this.SAMPLER3DBGRMAP = false;
  36211. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  36212. _this.EXPOSURE = false;
  36213. _this.USEPHYSICALLIGHTFALLOFF = false;
  36214. _this.TWOSIDEDLIGHTING = false;
  36215. _this.SHADOWFLOAT = false;
  36216. _this.CLIPPLANE = false;
  36217. _this.POINTSIZE = false;
  36218. _this.FOG = false;
  36219. _this.LOGARITHMICDEPTH = false;
  36220. _this.FORCENORMALFORWARD = false;
  36221. _this.rebuild();
  36222. return _this;
  36223. }
  36224. PBRMaterialDefines.prototype.reset = function () {
  36225. _super.prototype.reset.call(this);
  36226. this.ALPHATESTVALUE = 0.5;
  36227. this.PBR = true;
  36228. };
  36229. return PBRMaterialDefines;
  36230. }(BABYLON.MaterialDefines));
  36231. /**
  36232. * The Physically based material base class of BJS.
  36233. *
  36234. * This offers the main features of a standard PBR material.
  36235. * For more information, please refer to the documentation :
  36236. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  36237. */
  36238. var PBRBaseMaterial = /** @class */ (function (_super) {
  36239. __extends(PBRBaseMaterial, _super);
  36240. /**
  36241. * Instantiates a new PBRMaterial instance.
  36242. *
  36243. * @param name The material name
  36244. * @param scene The scene the material will be use in.
  36245. */
  36246. function PBRBaseMaterial(name, scene) {
  36247. var _this = _super.call(this, name, scene) || this;
  36248. /**
  36249. * Intensity of the direct lights e.g. the four lights available in your scene.
  36250. * This impacts both the direct diffuse and specular highlights.
  36251. */
  36252. _this._directIntensity = 1.0;
  36253. /**
  36254. * Intensity of the emissive part of the material.
  36255. * This helps controlling the emissive effect without modifying the emissive color.
  36256. */
  36257. _this._emissiveIntensity = 1.0;
  36258. /**
  36259. * Intensity of the environment e.g. how much the environment will light the object
  36260. * either through harmonics for rough material or through the refelction for shiny ones.
  36261. */
  36262. _this._environmentIntensity = 1.0;
  36263. /**
  36264. * This is a special control allowing the reduction of the specular highlights coming from the
  36265. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  36266. */
  36267. _this._specularIntensity = 1.0;
  36268. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  36269. /**
  36270. * Debug Control allowing disabling the bump map on this material.
  36271. */
  36272. _this._disableBumpMap = false;
  36273. /**
  36274. * AKA Occlusion Texture Intensity in other nomenclature.
  36275. */
  36276. _this._ambientTextureStrength = 1.0;
  36277. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  36278. /**
  36279. * AKA Diffuse Color in other nomenclature.
  36280. */
  36281. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  36282. /**
  36283. * AKA Specular Color in other nomenclature.
  36284. */
  36285. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  36286. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  36287. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  36288. /**
  36289. * AKA Glossiness in other nomenclature.
  36290. */
  36291. _this._microSurface = 0.9;
  36292. /**
  36293. * source material index of refraction (IOR)' / 'destination material IOR.
  36294. */
  36295. _this._indexOfRefraction = 0.66;
  36296. /**
  36297. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  36298. */
  36299. _this._invertRefractionY = false;
  36300. /**
  36301. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  36302. * Materials half opaque for instance using refraction could benefit from this control.
  36303. */
  36304. _this._linkRefractionWithTransparency = false;
  36305. _this._useLightmapAsShadowmap = false;
  36306. /**
  36307. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  36308. * makes the reflect vector face the model (under horizon).
  36309. */
  36310. _this._useHorizonOcclusion = true;
  36311. /**
  36312. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  36313. * too much the area relying on ambient texture to define their ambient occlusion.
  36314. */
  36315. _this._useRadianceOcclusion = true;
  36316. /**
  36317. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  36318. */
  36319. _this._useAlphaFromAlbedoTexture = false;
  36320. /**
  36321. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  36322. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  36323. */
  36324. _this._useSpecularOverAlpha = true;
  36325. /**
  36326. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  36327. */
  36328. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  36329. /**
  36330. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  36331. */
  36332. _this._useRoughnessFromMetallicTextureAlpha = true;
  36333. /**
  36334. * Specifies if the metallic texture contains the roughness information in its green channel.
  36335. */
  36336. _this._useRoughnessFromMetallicTextureGreen = false;
  36337. /**
  36338. * Specifies if the metallic texture contains the metallness information in its blue channel.
  36339. */
  36340. _this._useMetallnessFromMetallicTextureBlue = false;
  36341. /**
  36342. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  36343. */
  36344. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  36345. /**
  36346. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  36347. */
  36348. _this._useAmbientInGrayScale = false;
  36349. /**
  36350. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  36351. * The material will try to infer what glossiness each pixel should be.
  36352. */
  36353. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  36354. /**
  36355. * BJS is using an harcoded light falloff based on a manually sets up range.
  36356. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  36357. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  36358. */
  36359. _this._usePhysicalLightFalloff = true;
  36360. /**
  36361. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  36362. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  36363. */
  36364. _this._useRadianceOverAlpha = true;
  36365. /**
  36366. * Allows using the bump map in parallax mode.
  36367. */
  36368. _this._useParallax = false;
  36369. /**
  36370. * Allows using the bump map in parallax occlusion mode.
  36371. */
  36372. _this._useParallaxOcclusion = false;
  36373. /**
  36374. * Controls the scale bias of the parallax mode.
  36375. */
  36376. _this._parallaxScaleBias = 0.05;
  36377. /**
  36378. * If sets to true, disables all the lights affecting the material.
  36379. */
  36380. _this._disableLighting = false;
  36381. /**
  36382. * Number of Simultaneous lights allowed on the material.
  36383. */
  36384. _this._maxSimultaneousLights = 4;
  36385. /**
  36386. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  36387. */
  36388. _this._invertNormalMapX = false;
  36389. /**
  36390. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  36391. */
  36392. _this._invertNormalMapY = false;
  36393. /**
  36394. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36395. */
  36396. _this._twoSidedLighting = false;
  36397. /**
  36398. * Defines the alpha limits in alpha test mode.
  36399. */
  36400. _this._alphaCutOff = 0.4;
  36401. /**
  36402. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  36403. */
  36404. _this._forceAlphaTest = false;
  36405. /**
  36406. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36407. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  36408. */
  36409. _this._useAlphaFresnel = false;
  36410. /**
  36411. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36412. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  36413. */
  36414. _this._useLinearAlphaFresnel = false;
  36415. /**
  36416. * The transparency mode of the material.
  36417. */
  36418. _this._transparencyMode = null;
  36419. /**
  36420. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  36421. * from cos thetav and roughness:
  36422. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  36423. */
  36424. _this._environmentBRDFTexture = null;
  36425. /**
  36426. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  36427. */
  36428. _this._forceIrradianceInFragment = false;
  36429. /**
  36430. * Force normal to face away from face.
  36431. */
  36432. _this._forceNormalForward = false;
  36433. _this._renderTargets = new BABYLON.SmartArray(16);
  36434. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  36435. // Setup the default processing configuration to the scene.
  36436. _this._attachImageProcessingConfiguration(null);
  36437. _this.getRenderTargetTextures = function () {
  36438. _this._renderTargets.reset();
  36439. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  36440. _this._renderTargets.push(_this._reflectionTexture);
  36441. }
  36442. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  36443. _this._renderTargets.push(_this._refractionTexture);
  36444. }
  36445. return _this._renderTargets;
  36446. };
  36447. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  36448. return _this;
  36449. }
  36450. /**
  36451. * Attaches a new image processing configuration to the PBR Material.
  36452. * @param configuration
  36453. */
  36454. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  36455. var _this = this;
  36456. if (configuration === this._imageProcessingConfiguration) {
  36457. return;
  36458. }
  36459. // Detaches observer.
  36460. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  36461. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  36462. }
  36463. // Pick the scene configuration if needed.
  36464. if (!configuration) {
  36465. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  36466. }
  36467. else {
  36468. this._imageProcessingConfiguration = configuration;
  36469. }
  36470. // Attaches observer.
  36471. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  36472. _this._markAllSubMeshesAsImageProcessingDirty();
  36473. });
  36474. };
  36475. PBRBaseMaterial.prototype.getClassName = function () {
  36476. return "PBRBaseMaterial";
  36477. };
  36478. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  36479. get: function () {
  36480. return this._useLogarithmicDepth;
  36481. },
  36482. set: function (value) {
  36483. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  36484. },
  36485. enumerable: true,
  36486. configurable: true
  36487. });
  36488. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  36489. /**
  36490. * Gets the current transparency mode.
  36491. */
  36492. get: function () {
  36493. return this._transparencyMode;
  36494. },
  36495. /**
  36496. * Sets the transparency mode of the material.
  36497. */
  36498. set: function (value) {
  36499. if (this._transparencyMode === value) {
  36500. return;
  36501. }
  36502. this._transparencyMode = value;
  36503. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  36504. this._markAllSubMeshesAsTexturesDirty();
  36505. },
  36506. enumerable: true,
  36507. configurable: true
  36508. });
  36509. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  36510. /**
  36511. * Returns true if alpha blending should be disabled.
  36512. */
  36513. get: function () {
  36514. return (this._linkRefractionWithTransparency ||
  36515. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  36516. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  36517. },
  36518. enumerable: true,
  36519. configurable: true
  36520. });
  36521. /**
  36522. * Specifies whether or not this material should be rendered in alpha blend mode.
  36523. */
  36524. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  36525. if (this._disableAlphaBlending) {
  36526. return false;
  36527. }
  36528. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  36529. };
  36530. /**
  36531. * Specifies whether or not this material should be rendered in alpha blend mode for the given mesh.
  36532. */
  36533. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  36534. if (this._disableAlphaBlending) {
  36535. return false;
  36536. }
  36537. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  36538. };
  36539. /**
  36540. * Specifies whether or not this material should be rendered in alpha test mode.
  36541. */
  36542. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  36543. if (this._forceAlphaTest) {
  36544. return true;
  36545. }
  36546. if (this._linkRefractionWithTransparency) {
  36547. return false;
  36548. }
  36549. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  36550. };
  36551. /**
  36552. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  36553. */
  36554. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  36555. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  36556. };
  36557. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  36558. return this._albedoTexture;
  36559. };
  36560. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  36561. var _this = this;
  36562. if (subMesh.effect && this.isFrozen) {
  36563. if (this._wasPreviouslyReady) {
  36564. return true;
  36565. }
  36566. }
  36567. if (!subMesh._materialDefines) {
  36568. subMesh._materialDefines = new PBRMaterialDefines();
  36569. }
  36570. var scene = this.getScene();
  36571. var defines = subMesh._materialDefines;
  36572. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  36573. if (defines._renderId === scene.getRenderId()) {
  36574. return true;
  36575. }
  36576. }
  36577. var engine = scene.getEngine();
  36578. // Lights
  36579. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  36580. defines._needNormals = true;
  36581. // Textures
  36582. if (defines._areTexturesDirty) {
  36583. defines._needUVs = false;
  36584. if (scene.texturesEnabled) {
  36585. if (scene.getEngine().getCaps().textureLOD) {
  36586. defines.LODBASEDMICROSFURACE = true;
  36587. }
  36588. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  36589. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  36590. return false;
  36591. }
  36592. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  36593. }
  36594. else {
  36595. defines.ALBEDO = false;
  36596. }
  36597. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  36598. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  36599. return false;
  36600. }
  36601. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  36602. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  36603. }
  36604. else {
  36605. defines.AMBIENT = false;
  36606. }
  36607. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  36608. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  36609. return false;
  36610. }
  36611. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  36612. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  36613. }
  36614. else {
  36615. defines.OPACITY = false;
  36616. }
  36617. var reflectionTexture = this._getReflectionTexture();
  36618. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  36619. if (!reflectionTexture.isReadyOrNotBlocking()) {
  36620. return false;
  36621. }
  36622. defines.REFLECTION = true;
  36623. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  36624. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  36625. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  36626. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  36627. defines.INVERTCUBICMAP = true;
  36628. }
  36629. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  36630. switch (reflectionTexture.coordinatesMode) {
  36631. case BABYLON.Texture.CUBIC_MODE:
  36632. case BABYLON.Texture.INVCUBIC_MODE:
  36633. defines.REFLECTIONMAP_CUBIC = true;
  36634. break;
  36635. case BABYLON.Texture.EXPLICIT_MODE:
  36636. defines.REFLECTIONMAP_EXPLICIT = true;
  36637. break;
  36638. case BABYLON.Texture.PLANAR_MODE:
  36639. defines.REFLECTIONMAP_PLANAR = true;
  36640. break;
  36641. case BABYLON.Texture.PROJECTION_MODE:
  36642. defines.REFLECTIONMAP_PROJECTION = true;
  36643. break;
  36644. case BABYLON.Texture.SKYBOX_MODE:
  36645. defines.REFLECTIONMAP_SKYBOX = true;
  36646. break;
  36647. case BABYLON.Texture.SPHERICAL_MODE:
  36648. defines.REFLECTIONMAP_SPHERICAL = true;
  36649. break;
  36650. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  36651. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  36652. break;
  36653. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  36654. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  36655. break;
  36656. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  36657. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  36658. break;
  36659. }
  36660. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  36661. if (reflectionTexture.sphericalPolynomial) {
  36662. defines.USESPHERICALFROMREFLECTIONMAP = true;
  36663. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  36664. defines.USESPHERICALINVERTEX = false;
  36665. }
  36666. else {
  36667. defines.USESPHERICALINVERTEX = true;
  36668. }
  36669. }
  36670. }
  36671. }
  36672. else {
  36673. defines.REFLECTION = false;
  36674. defines.REFLECTIONMAP_3D = false;
  36675. defines.REFLECTIONMAP_SPHERICAL = false;
  36676. defines.REFLECTIONMAP_PLANAR = false;
  36677. defines.REFLECTIONMAP_CUBIC = false;
  36678. defines.REFLECTIONMAP_PROJECTION = false;
  36679. defines.REFLECTIONMAP_SKYBOX = false;
  36680. defines.REFLECTIONMAP_EXPLICIT = false;
  36681. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  36682. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  36683. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  36684. defines.INVERTCUBICMAP = false;
  36685. defines.USESPHERICALFROMREFLECTIONMAP = false;
  36686. defines.USESPHERICALINVERTEX = false;
  36687. defines.REFLECTIONMAP_OPPOSITEZ = false;
  36688. defines.LODINREFLECTIONALPHA = false;
  36689. defines.GAMMAREFLECTION = false;
  36690. }
  36691. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  36692. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  36693. return false;
  36694. }
  36695. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  36696. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  36697. }
  36698. else {
  36699. defines.LIGHTMAP = false;
  36700. }
  36701. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  36702. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  36703. return false;
  36704. }
  36705. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  36706. }
  36707. else {
  36708. defines.EMISSIVE = false;
  36709. }
  36710. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  36711. if (this._metallicTexture) {
  36712. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  36713. return false;
  36714. }
  36715. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  36716. defines.METALLICWORKFLOW = true;
  36717. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  36718. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  36719. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  36720. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  36721. }
  36722. else if (this._reflectivityTexture) {
  36723. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  36724. return false;
  36725. }
  36726. defines.METALLICWORKFLOW = false;
  36727. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  36728. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  36729. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  36730. }
  36731. else {
  36732. defines.METALLICWORKFLOW = false;
  36733. defines.REFLECTIVITY = false;
  36734. }
  36735. if (this._microSurfaceTexture) {
  36736. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  36737. return false;
  36738. }
  36739. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  36740. }
  36741. else {
  36742. defines.MICROSURFACEMAP = false;
  36743. }
  36744. }
  36745. else {
  36746. defines.REFLECTIVITY = false;
  36747. defines.MICROSURFACEMAP = false;
  36748. }
  36749. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  36750. // Bump texure can not be none blocking.
  36751. if (!this._bumpTexture.isReady()) {
  36752. return false;
  36753. }
  36754. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  36755. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  36756. defines.PARALLAX = true;
  36757. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  36758. }
  36759. else {
  36760. defines.PARALLAX = false;
  36761. }
  36762. }
  36763. else {
  36764. defines.BUMP = false;
  36765. }
  36766. var refractionTexture = this._getRefractionTexture();
  36767. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  36768. if (!refractionTexture.isReadyOrNotBlocking()) {
  36769. return false;
  36770. }
  36771. defines.REFRACTION = true;
  36772. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  36773. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  36774. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  36775. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  36776. if (this._linkRefractionWithTransparency) {
  36777. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  36778. }
  36779. }
  36780. else {
  36781. defines.REFRACTION = false;
  36782. }
  36783. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  36784. // This is blocking.
  36785. if (!this._environmentBRDFTexture.isReady()) {
  36786. return false;
  36787. }
  36788. defines.ENVIRONMENTBRDF = true;
  36789. }
  36790. else {
  36791. defines.ENVIRONMENTBRDF = false;
  36792. }
  36793. if (this._shouldUseAlphaFromAlbedoTexture()) {
  36794. defines.ALPHAFROMALBEDO = true;
  36795. }
  36796. else {
  36797. defines.ALPHAFROMALBEDO = false;
  36798. }
  36799. }
  36800. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  36801. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  36802. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  36803. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  36804. defines.METALLICWORKFLOW = true;
  36805. }
  36806. else {
  36807. defines.METALLICWORKFLOW = false;
  36808. }
  36809. if (!this.backFaceCulling && this._twoSidedLighting) {
  36810. defines.TWOSIDEDLIGHTING = true;
  36811. }
  36812. else {
  36813. defines.TWOSIDEDLIGHTING = false;
  36814. }
  36815. defines.ALPHATESTVALUE = this._alphaCutOff;
  36816. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  36817. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  36818. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  36819. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  36820. }
  36821. if (defines._areImageProcessingDirty) {
  36822. if (!this._imageProcessingConfiguration.isReady()) {
  36823. return false;
  36824. }
  36825. this._imageProcessingConfiguration.prepareDefines(defines);
  36826. }
  36827. defines.FORCENORMALFORWARD = this._forceNormalForward;
  36828. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  36829. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  36830. // Misc.
  36831. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  36832. // Values that need to be evaluated on every frame
  36833. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, this._forceAlphaTest);
  36834. // Attribs
  36835. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE) && mesh) {
  36836. var bufferMesh = null;
  36837. if (mesh instanceof BABYLON.InstancedMesh) {
  36838. bufferMesh = mesh.sourceMesh;
  36839. }
  36840. else if (mesh instanceof BABYLON.Mesh) {
  36841. bufferMesh = mesh;
  36842. }
  36843. if (bufferMesh) {
  36844. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36845. // If the first normal's components is the zero vector in one of the submeshes, we have invalid normals
  36846. var normalVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.NormalKind);
  36847. var normals = normalVertexBuffer.getData();
  36848. var vertexBufferOffset = normalVertexBuffer.getOffset();
  36849. var strideSize = normalVertexBuffer.getStrideSize();
  36850. var offset = vertexBufferOffset + subMesh.indexStart * strideSize;
  36851. if (normals[offset] === 0 && normals[offset + 1] === 0 && normals[offset + 2] === 0) {
  36852. defines.NORMAL = false;
  36853. }
  36854. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36855. // If the first tangent's components is the zero vector in one of the submeshes, we have invalid tangents
  36856. var tangentVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.TangentKind);
  36857. var tangents = tangentVertexBuffer.getData();
  36858. var vertexBufferOffset_1 = tangentVertexBuffer.getOffset();
  36859. var strideSize_1 = tangentVertexBuffer.getStrideSize();
  36860. var offset_1 = vertexBufferOffset_1 + subMesh.indexStart * strideSize_1;
  36861. if (tangents[offset_1] === 0 && tangents[offset_1 + 1] === 0 && tangents[offset_1 + 2] === 0) {
  36862. defines.TANGENT = false;
  36863. }
  36864. }
  36865. }
  36866. else {
  36867. if (!scene.getEngine().getCaps().standardDerivatives) {
  36868. bufferMesh.createNormals(true);
  36869. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  36870. }
  36871. }
  36872. }
  36873. }
  36874. // Get correct effect
  36875. if (defines.isDirty) {
  36876. defines.markAsProcessed();
  36877. scene.resetCachedMaterial();
  36878. // Fallbacks
  36879. var fallbacks = new BABYLON.EffectFallbacks();
  36880. var fallbackRank = 0;
  36881. if (defines.USESPHERICALINVERTEX) {
  36882. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  36883. }
  36884. if (defines.FOG) {
  36885. fallbacks.addFallback(fallbackRank, "FOG");
  36886. }
  36887. if (defines.POINTSIZE) {
  36888. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  36889. }
  36890. if (defines.LOGARITHMICDEPTH) {
  36891. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  36892. }
  36893. if (defines.PARALLAX) {
  36894. fallbacks.addFallback(fallbackRank, "PARALLAX");
  36895. }
  36896. if (defines.PARALLAXOCCLUSION) {
  36897. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  36898. }
  36899. if (defines.ENVIRONMENTBRDF) {
  36900. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  36901. }
  36902. if (defines.TANGENT) {
  36903. fallbacks.addFallback(fallbackRank++, "TANGENT");
  36904. }
  36905. if (defines.BUMP) {
  36906. fallbacks.addFallback(fallbackRank++, "BUMP");
  36907. }
  36908. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  36909. if (defines.SPECULARTERM) {
  36910. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  36911. }
  36912. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  36913. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  36914. }
  36915. if (defines.LIGHTMAP) {
  36916. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  36917. }
  36918. if (defines.NORMAL) {
  36919. fallbacks.addFallback(fallbackRank++, "NORMAL");
  36920. }
  36921. if (defines.AMBIENT) {
  36922. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  36923. }
  36924. if (defines.EMISSIVE) {
  36925. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  36926. }
  36927. if (defines.VERTEXCOLOR) {
  36928. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  36929. }
  36930. if (defines.NUM_BONE_INFLUENCERS > 0) {
  36931. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  36932. }
  36933. if (defines.MORPHTARGETS) {
  36934. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  36935. }
  36936. //Attributes
  36937. var attribs = [BABYLON.VertexBuffer.PositionKind];
  36938. if (defines.NORMAL) {
  36939. attribs.push(BABYLON.VertexBuffer.NormalKind);
  36940. }
  36941. if (defines.TANGENT) {
  36942. attribs.push(BABYLON.VertexBuffer.TangentKind);
  36943. }
  36944. if (defines.UV1) {
  36945. attribs.push(BABYLON.VertexBuffer.UVKind);
  36946. }
  36947. if (defines.UV2) {
  36948. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  36949. }
  36950. if (defines.VERTEXCOLOR) {
  36951. attribs.push(BABYLON.VertexBuffer.ColorKind);
  36952. }
  36953. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  36954. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  36955. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  36956. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  36957. "vFogInfos", "vFogColor", "pointSize",
  36958. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  36959. "mBones",
  36960. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  36961. "vLightingIntensity",
  36962. "logarithmicDepthConstant",
  36963. "vSphericalX", "vSphericalY", "vSphericalZ",
  36964. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  36965. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  36966. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  36967. "vTangentSpaceParams"
  36968. ];
  36969. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  36970. "bumpSampler", "lightmapSampler", "opacitySampler",
  36971. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  36972. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  36973. "microSurfaceSampler", "environmentBrdfSampler"];
  36974. var uniformBuffers = ["Material", "Scene"];
  36975. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  36976. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  36977. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  36978. uniformsNames: uniforms,
  36979. uniformBuffersNames: uniformBuffers,
  36980. samplers: samplers,
  36981. defines: defines,
  36982. maxSimultaneousLights: this._maxSimultaneousLights
  36983. });
  36984. var onCompiled = function (effect) {
  36985. if (_this.onCompiled) {
  36986. _this.onCompiled(effect);
  36987. }
  36988. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  36989. };
  36990. var join = defines.toString();
  36991. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  36992. attributes: attribs,
  36993. uniformsNames: uniforms,
  36994. uniformBuffersNames: uniformBuffers,
  36995. samplers: samplers,
  36996. defines: join,
  36997. fallbacks: fallbacks,
  36998. onCompiled: onCompiled,
  36999. onError: this.onError,
  37000. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  37001. }, engine), defines);
  37002. this.buildUniformLayout();
  37003. }
  37004. if (!subMesh.effect || !subMesh.effect.isReady()) {
  37005. return false;
  37006. }
  37007. defines._renderId = scene.getRenderId();
  37008. this._wasPreviouslyReady = true;
  37009. return true;
  37010. };
  37011. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  37012. // Order is important !
  37013. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  37014. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  37015. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  37016. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  37017. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  37018. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  37019. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  37020. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  37021. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  37022. this._uniformBuffer.addUniform("vBumpInfos", 3);
  37023. this._uniformBuffer.addUniform("albedoMatrix", 16);
  37024. this._uniformBuffer.addUniform("ambientMatrix", 16);
  37025. this._uniformBuffer.addUniform("opacityMatrix", 16);
  37026. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  37027. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  37028. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  37029. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  37030. this._uniformBuffer.addUniform("bumpMatrix", 16);
  37031. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  37032. this._uniformBuffer.addUniform("refractionMatrix", 16);
  37033. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  37034. this._uniformBuffer.addUniform("vReflectionColor", 3);
  37035. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  37036. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  37037. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  37038. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  37039. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  37040. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  37041. this._uniformBuffer.addUniform("pointSize", 1);
  37042. this._uniformBuffer.create();
  37043. };
  37044. PBRBaseMaterial.prototype.unbind = function () {
  37045. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  37046. this._uniformBuffer.setTexture("reflectionSampler", null);
  37047. }
  37048. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  37049. this._uniformBuffer.setTexture("refractionSampler", null);
  37050. }
  37051. _super.prototype.unbind.call(this);
  37052. };
  37053. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  37054. this._activeEffect.setMatrix("world", world);
  37055. };
  37056. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  37057. var scene = this.getScene();
  37058. var defines = subMesh._materialDefines;
  37059. if (!defines) {
  37060. return;
  37061. }
  37062. var effect = subMesh.effect;
  37063. if (!effect) {
  37064. return;
  37065. }
  37066. this._activeEffect = effect;
  37067. // Matrices
  37068. this.bindOnlyWorldMatrix(world);
  37069. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  37070. // Bones
  37071. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  37072. var reflectionTexture = null;
  37073. if (mustRebind) {
  37074. this._uniformBuffer.bindToEffect(effect, "Material");
  37075. this.bindViewProjection(effect);
  37076. reflectionTexture = this._getReflectionTexture();
  37077. var refractionTexture = this._getRefractionTexture();
  37078. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  37079. // Texture uniforms
  37080. if (scene.texturesEnabled) {
  37081. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37082. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  37083. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  37084. }
  37085. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  37086. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  37087. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  37088. }
  37089. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  37090. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  37091. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  37092. }
  37093. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37094. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  37095. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  37096. var polynomials = reflectionTexture.sphericalPolynomial;
  37097. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  37098. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  37099. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  37100. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  37101. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  37102. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  37103. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  37104. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  37105. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  37106. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  37107. }
  37108. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  37109. }
  37110. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37111. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  37112. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  37113. }
  37114. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37115. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  37116. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  37117. }
  37118. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37119. if (this._metallicTexture) {
  37120. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  37121. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  37122. }
  37123. else if (this._reflectivityTexture) {
  37124. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  37125. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  37126. }
  37127. if (this._microSurfaceTexture) {
  37128. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  37129. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  37130. }
  37131. }
  37132. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37133. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  37134. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  37135. if (scene._mirroredCameraPosition) {
  37136. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  37137. }
  37138. else {
  37139. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  37140. }
  37141. }
  37142. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37143. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  37144. var depth = 1.0;
  37145. if (!refractionTexture.isCube) {
  37146. if (refractionTexture.depth) {
  37147. depth = refractionTexture.depth;
  37148. }
  37149. }
  37150. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  37151. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  37152. }
  37153. }
  37154. // Point size
  37155. if (this.pointsCloud) {
  37156. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  37157. }
  37158. // Colors
  37159. if (defines.METALLICWORKFLOW) {
  37160. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  37161. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  37162. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  37163. }
  37164. else {
  37165. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  37166. }
  37167. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  37168. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  37169. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  37170. // Misc
  37171. this._lightingInfos.x = this._directIntensity;
  37172. this._lightingInfos.y = this._emissiveIntensity;
  37173. this._lightingInfos.z = this._environmentIntensity;
  37174. this._lightingInfos.w = this._specularIntensity;
  37175. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  37176. }
  37177. // Textures
  37178. if (scene.texturesEnabled) {
  37179. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37180. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  37181. }
  37182. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  37183. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  37184. }
  37185. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  37186. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  37187. }
  37188. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37189. if (defines.LODBASEDMICROSFURACE) {
  37190. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  37191. }
  37192. else {
  37193. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  37194. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  37195. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  37196. }
  37197. }
  37198. if (defines.ENVIRONMENTBRDF) {
  37199. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  37200. }
  37201. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37202. if (defines.LODBASEDMICROSFURACE) {
  37203. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  37204. }
  37205. else {
  37206. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  37207. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  37208. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  37209. }
  37210. }
  37211. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37212. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  37213. }
  37214. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37215. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  37216. }
  37217. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37218. if (this._metallicTexture) {
  37219. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  37220. }
  37221. else if (this._reflectivityTexture) {
  37222. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  37223. }
  37224. if (this._microSurfaceTexture) {
  37225. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  37226. }
  37227. }
  37228. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37229. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  37230. }
  37231. }
  37232. // Clip plane
  37233. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  37234. // Colors
  37235. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  37236. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  37237. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  37238. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  37239. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  37240. }
  37241. if (mustRebind || !this.isFrozen) {
  37242. // Lights
  37243. if (scene.lightsEnabled && !this._disableLighting) {
  37244. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  37245. }
  37246. // View
  37247. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  37248. this.bindView(effect);
  37249. }
  37250. // Fog
  37251. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  37252. // Morph targets
  37253. if (defines.NUM_MORPH_INFLUENCERS) {
  37254. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  37255. }
  37256. // image processing
  37257. this._imageProcessingConfiguration.bind(this._activeEffect);
  37258. // Log. depth
  37259. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  37260. }
  37261. this._uniformBuffer.update();
  37262. this._afterBind(mesh);
  37263. };
  37264. PBRBaseMaterial.prototype.getAnimatables = function () {
  37265. var results = [];
  37266. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  37267. results.push(this._albedoTexture);
  37268. }
  37269. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  37270. results.push(this._ambientTexture);
  37271. }
  37272. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  37273. results.push(this._opacityTexture);
  37274. }
  37275. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  37276. results.push(this._reflectionTexture);
  37277. }
  37278. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  37279. results.push(this._emissiveTexture);
  37280. }
  37281. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  37282. results.push(this._metallicTexture);
  37283. }
  37284. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  37285. results.push(this._reflectivityTexture);
  37286. }
  37287. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  37288. results.push(this._bumpTexture);
  37289. }
  37290. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  37291. results.push(this._lightmapTexture);
  37292. }
  37293. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  37294. results.push(this._refractionTexture);
  37295. }
  37296. return results;
  37297. };
  37298. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  37299. if (this._reflectionTexture) {
  37300. return this._reflectionTexture;
  37301. }
  37302. return this.getScene().environmentTexture;
  37303. };
  37304. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  37305. if (this._refractionTexture) {
  37306. return this._refractionTexture;
  37307. }
  37308. if (this._linkRefractionWithTransparency) {
  37309. return this.getScene().environmentTexture;
  37310. }
  37311. return null;
  37312. };
  37313. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  37314. if (forceDisposeTextures) {
  37315. if (this._albedoTexture) {
  37316. this._albedoTexture.dispose();
  37317. }
  37318. if (this._ambientTexture) {
  37319. this._ambientTexture.dispose();
  37320. }
  37321. if (this._opacityTexture) {
  37322. this._opacityTexture.dispose();
  37323. }
  37324. if (this._reflectionTexture) {
  37325. this._reflectionTexture.dispose();
  37326. }
  37327. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  37328. this._environmentBRDFTexture.dispose();
  37329. }
  37330. if (this._emissiveTexture) {
  37331. this._emissiveTexture.dispose();
  37332. }
  37333. if (this._metallicTexture) {
  37334. this._metallicTexture.dispose();
  37335. }
  37336. if (this._reflectivityTexture) {
  37337. this._reflectivityTexture.dispose();
  37338. }
  37339. if (this._bumpTexture) {
  37340. this._bumpTexture.dispose();
  37341. }
  37342. if (this._lightmapTexture) {
  37343. this._lightmapTexture.dispose();
  37344. }
  37345. if (this._refractionTexture) {
  37346. this._refractionTexture.dispose();
  37347. }
  37348. }
  37349. this._renderTargets.dispose();
  37350. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  37351. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  37352. }
  37353. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  37354. };
  37355. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  37356. __decorate([
  37357. BABYLON.serializeAsImageProcessingConfiguration()
  37358. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  37359. __decorate([
  37360. BABYLON.serialize()
  37361. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  37362. __decorate([
  37363. BABYLON.serialize()
  37364. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  37365. return PBRBaseMaterial;
  37366. }(BABYLON.PushMaterial));
  37367. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  37368. })(BABYLON || (BABYLON = {}));
  37369. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  37370. var BABYLON;
  37371. (function (BABYLON) {
  37372. var Internals;
  37373. (function (Internals) {
  37374. /**
  37375. * The Physically based simple base material of BJS.
  37376. *
  37377. * This enables better naming and convention enforcements on top of the pbrMaterial.
  37378. * It is used as the base class for both the specGloss and metalRough conventions.
  37379. */
  37380. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  37381. __extends(PBRBaseSimpleMaterial, _super);
  37382. /**
  37383. * Instantiates a new PBRMaterial instance.
  37384. *
  37385. * @param name The material name
  37386. * @param scene The scene the material will be use in.
  37387. */
  37388. function PBRBaseSimpleMaterial(name, scene) {
  37389. var _this = _super.call(this, name, scene) || this;
  37390. /**
  37391. * Number of Simultaneous lights allowed on the material.
  37392. */
  37393. _this.maxSimultaneousLights = 4;
  37394. /**
  37395. * If sets to true, disables all the lights affecting the material.
  37396. */
  37397. _this.disableLighting = false;
  37398. /**
  37399. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  37400. */
  37401. _this.invertNormalMapX = false;
  37402. /**
  37403. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  37404. */
  37405. _this.invertNormalMapY = false;
  37406. /**
  37407. * Emissivie color used to self-illuminate the model.
  37408. */
  37409. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  37410. /**
  37411. * Occlusion Channel Strenght.
  37412. */
  37413. _this.occlusionStrength = 1.0;
  37414. _this.useLightmapAsShadowmap = false;
  37415. _this._useAlphaFromAlbedoTexture = true;
  37416. _this._useAmbientInGrayScale = true;
  37417. return _this;
  37418. }
  37419. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  37420. /**
  37421. * Gets the current double sided mode.
  37422. */
  37423. get: function () {
  37424. return this._twoSidedLighting;
  37425. },
  37426. /**
  37427. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  37428. */
  37429. set: function (value) {
  37430. if (this._twoSidedLighting === value) {
  37431. return;
  37432. }
  37433. this._twoSidedLighting = value;
  37434. this.backFaceCulling = !value;
  37435. this._markAllSubMeshesAsTexturesDirty();
  37436. },
  37437. enumerable: true,
  37438. configurable: true
  37439. });
  37440. /**
  37441. * Return the active textures of the material.
  37442. */
  37443. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  37444. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37445. if (this.environmentTexture) {
  37446. activeTextures.push(this.environmentTexture);
  37447. }
  37448. if (this.normalTexture) {
  37449. activeTextures.push(this.normalTexture);
  37450. }
  37451. if (this.emissiveTexture) {
  37452. activeTextures.push(this.emissiveTexture);
  37453. }
  37454. if (this.occlusionTexture) {
  37455. activeTextures.push(this.occlusionTexture);
  37456. }
  37457. if (this.lightmapTexture) {
  37458. activeTextures.push(this.lightmapTexture);
  37459. }
  37460. return activeTextures;
  37461. };
  37462. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  37463. if (_super.prototype.hasTexture.call(this, texture)) {
  37464. return true;
  37465. }
  37466. if (this.lightmapTexture === texture) {
  37467. return true;
  37468. }
  37469. return false;
  37470. };
  37471. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  37472. return "PBRBaseSimpleMaterial";
  37473. };
  37474. __decorate([
  37475. BABYLON.serialize(),
  37476. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37477. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  37478. __decorate([
  37479. BABYLON.serialize(),
  37480. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37481. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  37482. __decorate([
  37483. BABYLON.serializeAsTexture(),
  37484. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  37485. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  37486. __decorate([
  37487. BABYLON.serialize(),
  37488. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37489. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  37490. __decorate([
  37491. BABYLON.serialize(),
  37492. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37493. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  37494. __decorate([
  37495. BABYLON.serializeAsTexture(),
  37496. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  37497. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  37498. __decorate([
  37499. BABYLON.serializeAsColor3("emissive"),
  37500. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37501. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  37502. __decorate([
  37503. BABYLON.serializeAsTexture(),
  37504. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37505. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  37506. __decorate([
  37507. BABYLON.serialize(),
  37508. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  37509. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  37510. __decorate([
  37511. BABYLON.serializeAsTexture(),
  37512. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  37513. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  37514. __decorate([
  37515. BABYLON.serialize(),
  37516. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  37517. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  37518. __decorate([
  37519. BABYLON.serialize()
  37520. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  37521. __decorate([
  37522. BABYLON.serializeAsTexture(),
  37523. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  37524. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  37525. __decorate([
  37526. BABYLON.serialize(),
  37527. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37528. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  37529. return PBRBaseSimpleMaterial;
  37530. }(BABYLON.PBRBaseMaterial));
  37531. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  37532. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  37533. })(BABYLON || (BABYLON = {}));
  37534. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  37535. var BABYLON;
  37536. (function (BABYLON) {
  37537. /**
  37538. * The Physically based material of BJS.
  37539. *
  37540. * This offers the main features of a standard PBR material.
  37541. * For more information, please refer to the documentation :
  37542. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  37543. */
  37544. var PBRMaterial = /** @class */ (function (_super) {
  37545. __extends(PBRMaterial, _super);
  37546. /**
  37547. * Instantiates a new PBRMaterial instance.
  37548. *
  37549. * @param name The material name
  37550. * @param scene The scene the material will be use in.
  37551. */
  37552. function PBRMaterial(name, scene) {
  37553. var _this = _super.call(this, name, scene) || this;
  37554. /**
  37555. * Intensity of the direct lights e.g. the four lights available in your scene.
  37556. * This impacts both the direct diffuse and specular highlights.
  37557. */
  37558. _this.directIntensity = 1.0;
  37559. /**
  37560. * Intensity of the emissive part of the material.
  37561. * This helps controlling the emissive effect without modifying the emissive color.
  37562. */
  37563. _this.emissiveIntensity = 1.0;
  37564. /**
  37565. * Intensity of the environment e.g. how much the environment will light the object
  37566. * either through harmonics for rough material or through the refelction for shiny ones.
  37567. */
  37568. _this.environmentIntensity = 1.0;
  37569. /**
  37570. * This is a special control allowing the reduction of the specular highlights coming from the
  37571. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  37572. */
  37573. _this.specularIntensity = 1.0;
  37574. /**
  37575. * Debug Control allowing disabling the bump map on this material.
  37576. */
  37577. _this.disableBumpMap = false;
  37578. /**
  37579. * AKA Occlusion Texture Intensity in other nomenclature.
  37580. */
  37581. _this.ambientTextureStrength = 1.0;
  37582. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  37583. /**
  37584. * AKA Diffuse Color in other nomenclature.
  37585. */
  37586. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  37587. /**
  37588. * AKA Specular Color in other nomenclature.
  37589. */
  37590. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  37591. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  37592. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  37593. /**
  37594. * AKA Glossiness in other nomenclature.
  37595. */
  37596. _this.microSurface = 1.0;
  37597. /**
  37598. * source material index of refraction (IOR)' / 'destination material IOR.
  37599. */
  37600. _this.indexOfRefraction = 0.66;
  37601. /**
  37602. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  37603. */
  37604. _this.invertRefractionY = false;
  37605. /**
  37606. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  37607. * Materials half opaque for instance using refraction could benefit from this control.
  37608. */
  37609. _this.linkRefractionWithTransparency = false;
  37610. _this.useLightmapAsShadowmap = false;
  37611. /**
  37612. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  37613. */
  37614. _this.useAlphaFromAlbedoTexture = false;
  37615. /**
  37616. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  37617. */
  37618. _this.forceAlphaTest = false;
  37619. /**
  37620. * Defines the alpha limits in alpha test mode.
  37621. */
  37622. _this.alphaCutOff = 0.4;
  37623. /**
  37624. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  37625. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  37626. */
  37627. _this.useSpecularOverAlpha = true;
  37628. /**
  37629. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  37630. */
  37631. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  37632. /**
  37633. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  37634. */
  37635. _this.useRoughnessFromMetallicTextureAlpha = true;
  37636. /**
  37637. * Specifies if the metallic texture contains the roughness information in its green channel.
  37638. */
  37639. _this.useRoughnessFromMetallicTextureGreen = false;
  37640. /**
  37641. * Specifies if the metallic texture contains the metallness information in its blue channel.
  37642. */
  37643. _this.useMetallnessFromMetallicTextureBlue = false;
  37644. /**
  37645. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  37646. */
  37647. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  37648. /**
  37649. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  37650. */
  37651. _this.useAmbientInGrayScale = false;
  37652. /**
  37653. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  37654. * The material will try to infer what glossiness each pixel should be.
  37655. */
  37656. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  37657. /**
  37658. * BJS is using an harcoded light falloff based on a manually sets up range.
  37659. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  37660. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  37661. */
  37662. _this.usePhysicalLightFalloff = true;
  37663. /**
  37664. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  37665. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  37666. */
  37667. _this.useRadianceOverAlpha = true;
  37668. /**
  37669. * Allows using the bump map in parallax mode.
  37670. */
  37671. _this.useParallax = false;
  37672. /**
  37673. * Allows using the bump map in parallax occlusion mode.
  37674. */
  37675. _this.useParallaxOcclusion = false;
  37676. /**
  37677. * Controls the scale bias of the parallax mode.
  37678. */
  37679. _this.parallaxScaleBias = 0.05;
  37680. /**
  37681. * If sets to true, disables all the lights affecting the material.
  37682. */
  37683. _this.disableLighting = false;
  37684. /**
  37685. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  37686. */
  37687. _this.forceIrradianceInFragment = false;
  37688. /**
  37689. * Number of Simultaneous lights allowed on the material.
  37690. */
  37691. _this.maxSimultaneousLights = 4;
  37692. /**
  37693. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  37694. */
  37695. _this.invertNormalMapX = false;
  37696. /**
  37697. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  37698. */
  37699. _this.invertNormalMapY = false;
  37700. /**
  37701. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  37702. */
  37703. _this.twoSidedLighting = false;
  37704. /**
  37705. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  37706. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  37707. */
  37708. _this.useAlphaFresnel = false;
  37709. /**
  37710. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  37711. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  37712. */
  37713. _this.useLinearAlphaFresnel = false;
  37714. /**
  37715. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  37716. * And/Or occlude the blended part.
  37717. */
  37718. _this.environmentBRDFTexture = null;
  37719. /**
  37720. * Force normal to face away from face.
  37721. */
  37722. _this.forceNormalForward = false;
  37723. /**
  37724. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  37725. * makes the reflect vector face the model (under horizon).
  37726. */
  37727. _this.useHorizonOcclusion = true;
  37728. /**
  37729. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  37730. * too much the area relying on ambient texture to define their ambient occlusion.
  37731. */
  37732. _this.useRadianceOcclusion = true;
  37733. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  37734. return _this;
  37735. }
  37736. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  37737. /**
  37738. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  37739. */
  37740. get: function () {
  37741. return this._PBRMATERIAL_OPAQUE;
  37742. },
  37743. enumerable: true,
  37744. configurable: true
  37745. });
  37746. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  37747. /**
  37748. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  37749. */
  37750. get: function () {
  37751. return this._PBRMATERIAL_ALPHATEST;
  37752. },
  37753. enumerable: true,
  37754. configurable: true
  37755. });
  37756. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  37757. /**
  37758. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  37759. */
  37760. get: function () {
  37761. return this._PBRMATERIAL_ALPHABLEND;
  37762. },
  37763. enumerable: true,
  37764. configurable: true
  37765. });
  37766. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  37767. /**
  37768. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  37769. * They are also discarded below the alpha cutoff threshold to improve performances.
  37770. */
  37771. get: function () {
  37772. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  37773. },
  37774. enumerable: true,
  37775. configurable: true
  37776. });
  37777. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  37778. /**
  37779. * Gets the image processing configuration used either in this material.
  37780. */
  37781. get: function () {
  37782. return this._imageProcessingConfiguration;
  37783. },
  37784. /**
  37785. * Sets the Default image processing configuration used either in the this material.
  37786. *
  37787. * If sets to null, the scene one is in use.
  37788. */
  37789. set: function (value) {
  37790. this._attachImageProcessingConfiguration(value);
  37791. // Ensure the effect will be rebuilt.
  37792. this._markAllSubMeshesAsTexturesDirty();
  37793. },
  37794. enumerable: true,
  37795. configurable: true
  37796. });
  37797. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  37798. /**
  37799. * Gets wether the color curves effect is enabled.
  37800. */
  37801. get: function () {
  37802. return this.imageProcessingConfiguration.colorCurvesEnabled;
  37803. },
  37804. /**
  37805. * Sets wether the color curves effect is enabled.
  37806. */
  37807. set: function (value) {
  37808. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  37809. },
  37810. enumerable: true,
  37811. configurable: true
  37812. });
  37813. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  37814. /**
  37815. * Gets wether the color grading effect is enabled.
  37816. */
  37817. get: function () {
  37818. return this.imageProcessingConfiguration.colorGradingEnabled;
  37819. },
  37820. /**
  37821. * Gets wether the color grading effect is enabled.
  37822. */
  37823. set: function (value) {
  37824. this.imageProcessingConfiguration.colorGradingEnabled = value;
  37825. },
  37826. enumerable: true,
  37827. configurable: true
  37828. });
  37829. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  37830. /**
  37831. * Gets wether tonemapping is enabled or not.
  37832. */
  37833. get: function () {
  37834. return this._imageProcessingConfiguration.toneMappingEnabled;
  37835. },
  37836. /**
  37837. * Sets wether tonemapping is enabled or not
  37838. */
  37839. set: function (value) {
  37840. this._imageProcessingConfiguration.toneMappingEnabled = value;
  37841. },
  37842. enumerable: true,
  37843. configurable: true
  37844. });
  37845. ;
  37846. ;
  37847. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  37848. /**
  37849. * The camera exposure used on this material.
  37850. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  37851. * This corresponds to a photographic exposure.
  37852. */
  37853. get: function () {
  37854. return this._imageProcessingConfiguration.exposure;
  37855. },
  37856. /**
  37857. * The camera exposure used on this material.
  37858. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  37859. * This corresponds to a photographic exposure.
  37860. */
  37861. set: function (value) {
  37862. this._imageProcessingConfiguration.exposure = value;
  37863. },
  37864. enumerable: true,
  37865. configurable: true
  37866. });
  37867. ;
  37868. ;
  37869. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  37870. /**
  37871. * Gets The camera contrast used on this material.
  37872. */
  37873. get: function () {
  37874. return this._imageProcessingConfiguration.contrast;
  37875. },
  37876. /**
  37877. * Sets The camera contrast used on this material.
  37878. */
  37879. set: function (value) {
  37880. this._imageProcessingConfiguration.contrast = value;
  37881. },
  37882. enumerable: true,
  37883. configurable: true
  37884. });
  37885. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  37886. /**
  37887. * Gets the Color Grading 2D Lookup Texture.
  37888. */
  37889. get: function () {
  37890. return this._imageProcessingConfiguration.colorGradingTexture;
  37891. },
  37892. /**
  37893. * Sets the Color Grading 2D Lookup Texture.
  37894. */
  37895. set: function (value) {
  37896. this._imageProcessingConfiguration.colorGradingTexture = value;
  37897. },
  37898. enumerable: true,
  37899. configurable: true
  37900. });
  37901. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  37902. /**
  37903. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37904. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37905. * 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;
  37906. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37907. */
  37908. get: function () {
  37909. return this._imageProcessingConfiguration.colorCurves;
  37910. },
  37911. /**
  37912. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37913. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37914. * 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;
  37915. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37916. */
  37917. set: function (value) {
  37918. this._imageProcessingConfiguration.colorCurves = value;
  37919. },
  37920. enumerable: true,
  37921. configurable: true
  37922. });
  37923. PBRMaterial.prototype.getClassName = function () {
  37924. return "PBRMaterial";
  37925. };
  37926. PBRMaterial.prototype.getActiveTextures = function () {
  37927. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37928. if (this._albedoTexture) {
  37929. activeTextures.push(this._albedoTexture);
  37930. }
  37931. if (this._ambientTexture) {
  37932. activeTextures.push(this._ambientTexture);
  37933. }
  37934. if (this._opacityTexture) {
  37935. activeTextures.push(this._opacityTexture);
  37936. }
  37937. if (this._reflectionTexture) {
  37938. activeTextures.push(this._reflectionTexture);
  37939. }
  37940. if (this._emissiveTexture) {
  37941. activeTextures.push(this._emissiveTexture);
  37942. }
  37943. if (this._reflectivityTexture) {
  37944. activeTextures.push(this._reflectivityTexture);
  37945. }
  37946. if (this._metallicTexture) {
  37947. activeTextures.push(this._metallicTexture);
  37948. }
  37949. if (this._microSurfaceTexture) {
  37950. activeTextures.push(this._microSurfaceTexture);
  37951. }
  37952. if (this._bumpTexture) {
  37953. activeTextures.push(this._bumpTexture);
  37954. }
  37955. if (this._lightmapTexture) {
  37956. activeTextures.push(this._lightmapTexture);
  37957. }
  37958. if (this._refractionTexture) {
  37959. activeTextures.push(this._refractionTexture);
  37960. }
  37961. return activeTextures;
  37962. };
  37963. PBRMaterial.prototype.hasTexture = function (texture) {
  37964. if (_super.prototype.hasTexture.call(this, texture)) {
  37965. return true;
  37966. }
  37967. if (this._albedoTexture === texture) {
  37968. return true;
  37969. }
  37970. if (this._ambientTexture === texture) {
  37971. return true;
  37972. }
  37973. if (this._opacityTexture === texture) {
  37974. return true;
  37975. }
  37976. if (this._reflectionTexture === texture) {
  37977. return true;
  37978. }
  37979. if (this._reflectivityTexture === texture) {
  37980. return true;
  37981. }
  37982. if (this._metallicTexture === texture) {
  37983. return true;
  37984. }
  37985. if (this._microSurfaceTexture === texture) {
  37986. return true;
  37987. }
  37988. if (this._bumpTexture === texture) {
  37989. return true;
  37990. }
  37991. if (this._lightmapTexture === texture) {
  37992. return true;
  37993. }
  37994. if (this._refractionTexture === texture) {
  37995. return true;
  37996. }
  37997. return false;
  37998. };
  37999. PBRMaterial.prototype.clone = function (name) {
  38000. var _this = this;
  38001. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  38002. clone.id = name;
  38003. clone.name = name;
  38004. return clone;
  38005. };
  38006. PBRMaterial.prototype.serialize = function () {
  38007. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38008. serializationObject.customType = "BABYLON.PBRMaterial";
  38009. return serializationObject;
  38010. };
  38011. // Statics
  38012. PBRMaterial.Parse = function (source, scene, rootUrl) {
  38013. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  38014. };
  38015. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  38016. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  38017. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  38018. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  38019. __decorate([
  38020. BABYLON.serialize(),
  38021. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38022. ], PBRMaterial.prototype, "directIntensity", void 0);
  38023. __decorate([
  38024. BABYLON.serialize(),
  38025. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38026. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  38027. __decorate([
  38028. BABYLON.serialize(),
  38029. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38030. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  38031. __decorate([
  38032. BABYLON.serialize(),
  38033. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38034. ], PBRMaterial.prototype, "specularIntensity", void 0);
  38035. __decorate([
  38036. BABYLON.serialize(),
  38037. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38038. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  38039. __decorate([
  38040. BABYLON.serializeAsTexture(),
  38041. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38042. ], PBRMaterial.prototype, "albedoTexture", void 0);
  38043. __decorate([
  38044. BABYLON.serializeAsTexture(),
  38045. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38046. ], PBRMaterial.prototype, "ambientTexture", void 0);
  38047. __decorate([
  38048. BABYLON.serialize(),
  38049. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38050. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  38051. __decorate([
  38052. BABYLON.serializeAsTexture(),
  38053. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38054. ], PBRMaterial.prototype, "opacityTexture", void 0);
  38055. __decorate([
  38056. BABYLON.serializeAsTexture(),
  38057. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38058. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  38059. __decorate([
  38060. BABYLON.serializeAsTexture(),
  38061. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38062. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  38063. __decorate([
  38064. BABYLON.serializeAsTexture(),
  38065. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38066. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  38067. __decorate([
  38068. BABYLON.serializeAsTexture(),
  38069. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38070. ], PBRMaterial.prototype, "metallicTexture", void 0);
  38071. __decorate([
  38072. BABYLON.serialize(),
  38073. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38074. ], PBRMaterial.prototype, "metallic", void 0);
  38075. __decorate([
  38076. BABYLON.serialize(),
  38077. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38078. ], PBRMaterial.prototype, "roughness", void 0);
  38079. __decorate([
  38080. BABYLON.serializeAsTexture(),
  38081. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38082. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  38083. __decorate([
  38084. BABYLON.serializeAsTexture(),
  38085. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38086. ], PBRMaterial.prototype, "bumpTexture", void 0);
  38087. __decorate([
  38088. BABYLON.serializeAsTexture(),
  38089. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  38090. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  38091. __decorate([
  38092. BABYLON.serializeAsTexture(),
  38093. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38094. ], PBRMaterial.prototype, "refractionTexture", void 0);
  38095. __decorate([
  38096. BABYLON.serializeAsColor3("ambient"),
  38097. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38098. ], PBRMaterial.prototype, "ambientColor", void 0);
  38099. __decorate([
  38100. BABYLON.serializeAsColor3("albedo"),
  38101. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38102. ], PBRMaterial.prototype, "albedoColor", void 0);
  38103. __decorate([
  38104. BABYLON.serializeAsColor3("reflectivity"),
  38105. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38106. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  38107. __decorate([
  38108. BABYLON.serializeAsColor3("reflection"),
  38109. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38110. ], PBRMaterial.prototype, "reflectionColor", void 0);
  38111. __decorate([
  38112. BABYLON.serializeAsColor3("emissive"),
  38113. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38114. ], PBRMaterial.prototype, "emissiveColor", void 0);
  38115. __decorate([
  38116. BABYLON.serialize(),
  38117. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38118. ], PBRMaterial.prototype, "microSurface", void 0);
  38119. __decorate([
  38120. BABYLON.serialize(),
  38121. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38122. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  38123. __decorate([
  38124. BABYLON.serialize(),
  38125. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38126. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  38127. __decorate([
  38128. BABYLON.serialize(),
  38129. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38130. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  38131. __decorate([
  38132. BABYLON.serialize(),
  38133. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38134. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  38135. __decorate([
  38136. BABYLON.serialize(),
  38137. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38138. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  38139. __decorate([
  38140. BABYLON.serialize(),
  38141. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38142. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  38143. __decorate([
  38144. BABYLON.serialize(),
  38145. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38146. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  38147. __decorate([
  38148. BABYLON.serialize(),
  38149. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38150. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  38151. __decorate([
  38152. BABYLON.serialize(),
  38153. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38154. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  38155. __decorate([
  38156. BABYLON.serialize(),
  38157. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38158. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  38159. __decorate([
  38160. BABYLON.serialize(),
  38161. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38162. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  38163. __decorate([
  38164. BABYLON.serialize(),
  38165. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38166. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  38167. __decorate([
  38168. BABYLON.serialize(),
  38169. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38170. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  38171. __decorate([
  38172. BABYLON.serialize(),
  38173. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38174. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  38175. __decorate([
  38176. BABYLON.serialize(),
  38177. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38178. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  38179. __decorate([
  38180. BABYLON.serialize(),
  38181. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38182. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  38183. __decorate([
  38184. BABYLON.serialize(),
  38185. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38186. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  38187. __decorate([
  38188. BABYLON.serialize(),
  38189. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38190. ], PBRMaterial.prototype, "useParallax", void 0);
  38191. __decorate([
  38192. BABYLON.serialize(),
  38193. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38194. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  38195. __decorate([
  38196. BABYLON.serialize(),
  38197. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38198. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  38199. __decorate([
  38200. BABYLON.serialize(),
  38201. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38202. ], PBRMaterial.prototype, "disableLighting", void 0);
  38203. __decorate([
  38204. BABYLON.serialize(),
  38205. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38206. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  38207. __decorate([
  38208. BABYLON.serialize(),
  38209. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38210. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  38211. __decorate([
  38212. BABYLON.serialize(),
  38213. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38214. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  38215. __decorate([
  38216. BABYLON.serialize(),
  38217. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38218. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  38219. __decorate([
  38220. BABYLON.serialize(),
  38221. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38222. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  38223. __decorate([
  38224. BABYLON.serialize(),
  38225. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38226. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  38227. __decorate([
  38228. BABYLON.serialize(),
  38229. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38230. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  38231. __decorate([
  38232. BABYLON.serializeAsTexture(),
  38233. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38234. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  38235. __decorate([
  38236. BABYLON.serialize(),
  38237. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38238. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  38239. __decorate([
  38240. BABYLON.serialize(),
  38241. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38242. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  38243. __decorate([
  38244. BABYLON.serialize(),
  38245. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38246. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  38247. return PBRMaterial;
  38248. }(BABYLON.PBRBaseMaterial));
  38249. BABYLON.PBRMaterial = PBRMaterial;
  38250. })(BABYLON || (BABYLON = {}));
  38251. //# sourceMappingURL=babylon.pbrMaterial.js.map
  38252. var BABYLON;
  38253. (function (BABYLON) {
  38254. /**
  38255. * The PBR material of BJS following the metal roughness convention.
  38256. *
  38257. * This fits to the PBR convention in the GLTF definition:
  38258. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  38259. */
  38260. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  38261. __extends(PBRMetallicRoughnessMaterial, _super);
  38262. /**
  38263. * Instantiates a new PBRMetalRoughnessMaterial instance.
  38264. *
  38265. * @param name The material name
  38266. * @param scene The scene the material will be use in.
  38267. */
  38268. function PBRMetallicRoughnessMaterial(name, scene) {
  38269. var _this = _super.call(this, name, scene) || this;
  38270. _this._useRoughnessFromMetallicTextureAlpha = false;
  38271. _this._useRoughnessFromMetallicTextureGreen = true;
  38272. _this._useMetallnessFromMetallicTextureBlue = true;
  38273. return _this;
  38274. }
  38275. /**
  38276. * Return the currrent class name of the material.
  38277. */
  38278. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  38279. return "PBRMetallicRoughnessMaterial";
  38280. };
  38281. /**
  38282. * Return the active textures of the material.
  38283. */
  38284. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  38285. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38286. if (this.baseTexture) {
  38287. activeTextures.push(this.baseTexture);
  38288. }
  38289. if (this.metallicRoughnessTexture) {
  38290. activeTextures.push(this.metallicRoughnessTexture);
  38291. }
  38292. return activeTextures;
  38293. };
  38294. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  38295. if (_super.prototype.hasTexture.call(this, texture)) {
  38296. return true;
  38297. }
  38298. if (this.baseTexture === texture) {
  38299. return true;
  38300. }
  38301. if (this.metallicRoughnessTexture === texture) {
  38302. return true;
  38303. }
  38304. return false;
  38305. };
  38306. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  38307. var _this = this;
  38308. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  38309. clone.id = name;
  38310. clone.name = name;
  38311. return clone;
  38312. };
  38313. /**
  38314. * Serialize the material to a parsable JSON object.
  38315. */
  38316. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  38317. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38318. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  38319. return serializationObject;
  38320. };
  38321. /**
  38322. * Parses a JSON object correponding to the serialize function.
  38323. */
  38324. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  38325. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  38326. };
  38327. __decorate([
  38328. BABYLON.serializeAsColor3(),
  38329. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  38330. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  38331. __decorate([
  38332. BABYLON.serializeAsTexture(),
  38333. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  38334. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  38335. __decorate([
  38336. BABYLON.serialize(),
  38337. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38338. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  38339. __decorate([
  38340. BABYLON.serialize(),
  38341. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38342. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  38343. __decorate([
  38344. BABYLON.serializeAsTexture(),
  38345. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  38346. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  38347. return PBRMetallicRoughnessMaterial;
  38348. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  38349. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  38350. })(BABYLON || (BABYLON = {}));
  38351. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  38352. var BABYLON;
  38353. (function (BABYLON) {
  38354. /**
  38355. * The PBR material of BJS following the specular glossiness convention.
  38356. *
  38357. * This fits to the PBR convention in the GLTF definition:
  38358. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  38359. */
  38360. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  38361. __extends(PBRSpecularGlossinessMaterial, _super);
  38362. /**
  38363. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  38364. *
  38365. * @param name The material name
  38366. * @param scene The scene the material will be use in.
  38367. */
  38368. function PBRSpecularGlossinessMaterial(name, scene) {
  38369. var _this = _super.call(this, name, scene) || this;
  38370. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  38371. return _this;
  38372. }
  38373. /**
  38374. * Return the currrent class name of the material.
  38375. */
  38376. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  38377. return "PBRSpecularGlossinessMaterial";
  38378. };
  38379. /**
  38380. * Return the active textures of the material.
  38381. */
  38382. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  38383. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38384. if (this.diffuseTexture) {
  38385. activeTextures.push(this.diffuseTexture);
  38386. }
  38387. if (this.specularGlossinessTexture) {
  38388. activeTextures.push(this.specularGlossinessTexture);
  38389. }
  38390. return activeTextures;
  38391. };
  38392. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  38393. if (_super.prototype.hasTexture.call(this, texture)) {
  38394. return true;
  38395. }
  38396. if (this.diffuseTexture === texture) {
  38397. return true;
  38398. }
  38399. if (this.specularGlossinessTexture === texture) {
  38400. return true;
  38401. }
  38402. return false;
  38403. };
  38404. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  38405. var _this = this;
  38406. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  38407. clone.id = name;
  38408. clone.name = name;
  38409. return clone;
  38410. };
  38411. /**
  38412. * Serialize the material to a parsable JSON object.
  38413. */
  38414. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  38415. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38416. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  38417. return serializationObject;
  38418. };
  38419. /**
  38420. * Parses a JSON object correponding to the serialize function.
  38421. */
  38422. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  38423. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  38424. };
  38425. __decorate([
  38426. BABYLON.serializeAsColor3("diffuse"),
  38427. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  38428. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  38429. __decorate([
  38430. BABYLON.serializeAsTexture(),
  38431. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  38432. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  38433. __decorate([
  38434. BABYLON.serializeAsColor3("specular"),
  38435. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  38436. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  38437. __decorate([
  38438. BABYLON.serialize(),
  38439. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  38440. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  38441. __decorate([
  38442. BABYLON.serializeAsTexture(),
  38443. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  38444. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  38445. return PBRSpecularGlossinessMaterial;
  38446. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  38447. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  38448. })(BABYLON || (BABYLON = {}));
  38449. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  38450. var BABYLON;
  38451. (function (BABYLON) {
  38452. BABYLON.CameraInputTypes = {};
  38453. var CameraInputsManager = /** @class */ (function () {
  38454. function CameraInputsManager(camera) {
  38455. this.attached = {};
  38456. this.camera = camera;
  38457. this.checkInputs = function () { };
  38458. }
  38459. CameraInputsManager.prototype.add = function (input) {
  38460. var type = input.getSimpleName();
  38461. if (this.attached[type]) {
  38462. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  38463. return;
  38464. }
  38465. this.attached[type] = input;
  38466. input.camera = this.camera;
  38467. //for checkInputs, we are dynamically creating a function
  38468. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  38469. if (input.checkInputs) {
  38470. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  38471. }
  38472. if (this.attachedElement) {
  38473. input.attachControl(this.attachedElement);
  38474. }
  38475. };
  38476. CameraInputsManager.prototype.remove = function (inputToRemove) {
  38477. for (var cam in this.attached) {
  38478. var input = this.attached[cam];
  38479. if (input === inputToRemove) {
  38480. input.detachControl(this.attachedElement);
  38481. input.camera = null;
  38482. delete this.attached[cam];
  38483. this.rebuildInputCheck();
  38484. }
  38485. }
  38486. };
  38487. CameraInputsManager.prototype.removeByType = function (inputType) {
  38488. for (var cam in this.attached) {
  38489. var input = this.attached[cam];
  38490. if (input.getClassName() === inputType) {
  38491. input.detachControl(this.attachedElement);
  38492. input.camera = null;
  38493. delete this.attached[cam];
  38494. this.rebuildInputCheck();
  38495. }
  38496. }
  38497. };
  38498. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  38499. var current = this.checkInputs;
  38500. return function () {
  38501. current();
  38502. fn();
  38503. };
  38504. };
  38505. CameraInputsManager.prototype.attachInput = function (input) {
  38506. if (this.attachedElement) {
  38507. input.attachControl(this.attachedElement, this.noPreventDefault);
  38508. }
  38509. };
  38510. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  38511. if (noPreventDefault === void 0) { noPreventDefault = false; }
  38512. if (this.attachedElement) {
  38513. return;
  38514. }
  38515. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  38516. this.attachedElement = element;
  38517. this.noPreventDefault = noPreventDefault;
  38518. for (var cam in this.attached) {
  38519. this.attached[cam].attachControl(element, noPreventDefault);
  38520. }
  38521. };
  38522. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  38523. if (disconnect === void 0) { disconnect = false; }
  38524. if (this.attachedElement !== element) {
  38525. return;
  38526. }
  38527. for (var cam in this.attached) {
  38528. this.attached[cam].detachControl(element);
  38529. if (disconnect) {
  38530. this.attached[cam].camera = null;
  38531. }
  38532. }
  38533. this.attachedElement = null;
  38534. };
  38535. CameraInputsManager.prototype.rebuildInputCheck = function () {
  38536. this.checkInputs = function () { };
  38537. for (var cam in this.attached) {
  38538. var input = this.attached[cam];
  38539. if (input.checkInputs) {
  38540. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  38541. }
  38542. }
  38543. };
  38544. CameraInputsManager.prototype.clear = function () {
  38545. if (this.attachedElement) {
  38546. this.detachElement(this.attachedElement, true);
  38547. }
  38548. this.attached = {};
  38549. this.attachedElement = null;
  38550. this.checkInputs = function () { };
  38551. };
  38552. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  38553. var inputs = {};
  38554. for (var cam in this.attached) {
  38555. var input = this.attached[cam];
  38556. var res = BABYLON.SerializationHelper.Serialize(input);
  38557. inputs[input.getClassName()] = res;
  38558. }
  38559. serializedCamera.inputsmgr = inputs;
  38560. };
  38561. CameraInputsManager.prototype.parse = function (parsedCamera) {
  38562. var parsedInputs = parsedCamera.inputsmgr;
  38563. if (parsedInputs) {
  38564. this.clear();
  38565. for (var n in parsedInputs) {
  38566. var construct = BABYLON.CameraInputTypes[n];
  38567. if (construct) {
  38568. var parsedinput = parsedInputs[n];
  38569. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  38570. this.add(input);
  38571. }
  38572. }
  38573. }
  38574. else {
  38575. //2016-03-08 this part is for managing backward compatibility
  38576. for (var n in this.attached) {
  38577. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  38578. if (construct) {
  38579. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  38580. this.remove(this.attached[n]);
  38581. this.add(input);
  38582. }
  38583. }
  38584. }
  38585. };
  38586. return CameraInputsManager;
  38587. }());
  38588. BABYLON.CameraInputsManager = CameraInputsManager;
  38589. })(BABYLON || (BABYLON = {}));
  38590. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  38591. var BABYLON;
  38592. (function (BABYLON) {
  38593. var FreeCameraMouseInput = /** @class */ (function () {
  38594. function FreeCameraMouseInput(touchEnabled) {
  38595. if (touchEnabled === void 0) { touchEnabled = true; }
  38596. this.touchEnabled = touchEnabled;
  38597. this.buttons = [0, 1, 2];
  38598. this.angularSensibility = 2000.0;
  38599. this.previousPosition = null;
  38600. }
  38601. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  38602. var _this = this;
  38603. var engine = this.camera.getEngine();
  38604. if (!this._pointerInput) {
  38605. this._pointerInput = function (p, s) {
  38606. var evt = p.event;
  38607. if (engine.isInVRExclusivePointerMode) {
  38608. return;
  38609. }
  38610. if (!_this.touchEnabled && evt.pointerType === "touch") {
  38611. return;
  38612. }
  38613. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  38614. return;
  38615. }
  38616. var srcElement = (evt.srcElement || evt.target);
  38617. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  38618. try {
  38619. srcElement.setPointerCapture(evt.pointerId);
  38620. }
  38621. catch (e) {
  38622. //Nothing to do with the error. Execution will continue.
  38623. }
  38624. _this.previousPosition = {
  38625. x: evt.clientX,
  38626. y: evt.clientY
  38627. };
  38628. if (!noPreventDefault) {
  38629. evt.preventDefault();
  38630. element.focus();
  38631. }
  38632. }
  38633. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  38634. try {
  38635. srcElement.releasePointerCapture(evt.pointerId);
  38636. }
  38637. catch (e) {
  38638. //Nothing to do with the error.
  38639. }
  38640. _this.previousPosition = null;
  38641. if (!noPreventDefault) {
  38642. evt.preventDefault();
  38643. }
  38644. }
  38645. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  38646. if (!_this.previousPosition || engine.isPointerLock) {
  38647. return;
  38648. }
  38649. var offsetX = evt.clientX - _this.previousPosition.x;
  38650. var offsetY = evt.clientY - _this.previousPosition.y;
  38651. if (_this.camera.getScene().useRightHandedSystem) {
  38652. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  38653. }
  38654. else {
  38655. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  38656. }
  38657. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  38658. _this.previousPosition = {
  38659. x: evt.clientX,
  38660. y: evt.clientY
  38661. };
  38662. if (!noPreventDefault) {
  38663. evt.preventDefault();
  38664. }
  38665. }
  38666. };
  38667. }
  38668. this._onMouseMove = function (evt) {
  38669. if (!engine.isPointerLock) {
  38670. return;
  38671. }
  38672. if (engine.isInVRExclusivePointerMode) {
  38673. return;
  38674. }
  38675. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  38676. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  38677. if (_this.camera.getScene().useRightHandedSystem) {
  38678. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  38679. }
  38680. else {
  38681. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  38682. }
  38683. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  38684. _this.previousPosition = null;
  38685. if (!noPreventDefault) {
  38686. evt.preventDefault();
  38687. }
  38688. };
  38689. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  38690. element.addEventListener("mousemove", this._onMouseMove, false);
  38691. };
  38692. FreeCameraMouseInput.prototype.detachControl = function (element) {
  38693. if (this._observer && element) {
  38694. this.camera.getScene().onPointerObservable.remove(this._observer);
  38695. if (this._onMouseMove) {
  38696. element.removeEventListener("mousemove", this._onMouseMove);
  38697. }
  38698. this._observer = null;
  38699. this._onMouseMove = null;
  38700. this.previousPosition = null;
  38701. }
  38702. };
  38703. FreeCameraMouseInput.prototype.getClassName = function () {
  38704. return "FreeCameraMouseInput";
  38705. };
  38706. FreeCameraMouseInput.prototype.getSimpleName = function () {
  38707. return "mouse";
  38708. };
  38709. __decorate([
  38710. BABYLON.serialize()
  38711. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  38712. __decorate([
  38713. BABYLON.serialize()
  38714. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  38715. return FreeCameraMouseInput;
  38716. }());
  38717. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  38718. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  38719. })(BABYLON || (BABYLON = {}));
  38720. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  38721. var BABYLON;
  38722. (function (BABYLON) {
  38723. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  38724. function FreeCameraKeyboardMoveInput() {
  38725. this._keys = new Array();
  38726. this.keysUp = [38];
  38727. this.keysDown = [40];
  38728. this.keysLeft = [37];
  38729. this.keysRight = [39];
  38730. }
  38731. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  38732. var _this = this;
  38733. if (this._onCanvasBlurObserver) {
  38734. return;
  38735. }
  38736. this._scene = this.camera.getScene();
  38737. this._engine = this._scene.getEngine();
  38738. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  38739. _this._keys = [];
  38740. });
  38741. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  38742. var evt = info.event;
  38743. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  38744. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  38745. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  38746. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  38747. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  38748. var index = _this._keys.indexOf(evt.keyCode);
  38749. if (index === -1) {
  38750. _this._keys.push(evt.keyCode);
  38751. }
  38752. if (!noPreventDefault) {
  38753. evt.preventDefault();
  38754. }
  38755. }
  38756. }
  38757. else {
  38758. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  38759. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  38760. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  38761. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  38762. var index = _this._keys.indexOf(evt.keyCode);
  38763. if (index >= 0) {
  38764. _this._keys.splice(index, 1);
  38765. }
  38766. if (!noPreventDefault) {
  38767. evt.preventDefault();
  38768. }
  38769. }
  38770. }
  38771. });
  38772. };
  38773. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  38774. if (this._scene) {
  38775. if (this._onKeyboardObserver) {
  38776. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  38777. }
  38778. if (this._onCanvasBlurObserver) {
  38779. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  38780. }
  38781. this._onKeyboardObserver = null;
  38782. this._onCanvasBlurObserver = null;
  38783. }
  38784. this._keys = [];
  38785. };
  38786. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  38787. if (this._onKeyboardObserver) {
  38788. var camera = this.camera;
  38789. // Keyboard
  38790. for (var index = 0; index < this._keys.length; index++) {
  38791. var keyCode = this._keys[index];
  38792. var speed = camera._computeLocalCameraSpeed();
  38793. if (this.keysLeft.indexOf(keyCode) !== -1) {
  38794. camera._localDirection.copyFromFloats(-speed, 0, 0);
  38795. }
  38796. else if (this.keysUp.indexOf(keyCode) !== -1) {
  38797. camera._localDirection.copyFromFloats(0, 0, speed);
  38798. }
  38799. else if (this.keysRight.indexOf(keyCode) !== -1) {
  38800. camera._localDirection.copyFromFloats(speed, 0, 0);
  38801. }
  38802. else if (this.keysDown.indexOf(keyCode) !== -1) {
  38803. camera._localDirection.copyFromFloats(0, 0, -speed);
  38804. }
  38805. if (camera.getScene().useRightHandedSystem) {
  38806. camera._localDirection.z *= -1;
  38807. }
  38808. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  38809. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  38810. camera.cameraDirection.addInPlace(camera._transformedDirection);
  38811. }
  38812. }
  38813. };
  38814. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  38815. return "FreeCameraKeyboardMoveInput";
  38816. };
  38817. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  38818. this._keys = [];
  38819. };
  38820. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  38821. return "keyboard";
  38822. };
  38823. __decorate([
  38824. BABYLON.serialize()
  38825. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  38826. __decorate([
  38827. BABYLON.serialize()
  38828. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  38829. __decorate([
  38830. BABYLON.serialize()
  38831. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  38832. __decorate([
  38833. BABYLON.serialize()
  38834. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  38835. return FreeCameraKeyboardMoveInput;
  38836. }());
  38837. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  38838. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  38839. })(BABYLON || (BABYLON = {}));
  38840. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  38841. var BABYLON;
  38842. (function (BABYLON) {
  38843. var FreeCameraInputsManager = /** @class */ (function (_super) {
  38844. __extends(FreeCameraInputsManager, _super);
  38845. function FreeCameraInputsManager(camera) {
  38846. return _super.call(this, camera) || this;
  38847. }
  38848. FreeCameraInputsManager.prototype.addKeyboard = function () {
  38849. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  38850. return this;
  38851. };
  38852. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  38853. if (touchEnabled === void 0) { touchEnabled = true; }
  38854. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  38855. return this;
  38856. };
  38857. FreeCameraInputsManager.prototype.addGamepad = function () {
  38858. this.add(new BABYLON.FreeCameraGamepadInput());
  38859. return this;
  38860. };
  38861. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  38862. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  38863. return this;
  38864. };
  38865. FreeCameraInputsManager.prototype.addTouch = function () {
  38866. this.add(new BABYLON.FreeCameraTouchInput());
  38867. return this;
  38868. };
  38869. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  38870. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  38871. return this;
  38872. };
  38873. return FreeCameraInputsManager;
  38874. }(BABYLON.CameraInputsManager));
  38875. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  38876. })(BABYLON || (BABYLON = {}));
  38877. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  38878. var BABYLON;
  38879. (function (BABYLON) {
  38880. var TargetCamera = /** @class */ (function (_super) {
  38881. __extends(TargetCamera, _super);
  38882. function TargetCamera(name, position, scene) {
  38883. var _this = _super.call(this, name, position, scene) || this;
  38884. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  38885. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  38886. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  38887. _this.speed = 2.0;
  38888. _this.noRotationConstraint = false;
  38889. _this.lockedTarget = null;
  38890. _this._currentTarget = BABYLON.Vector3.Zero();
  38891. _this._viewMatrix = BABYLON.Matrix.Zero();
  38892. _this._camMatrix = BABYLON.Matrix.Zero();
  38893. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  38894. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  38895. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  38896. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  38897. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  38898. _this._lookAtTemp = BABYLON.Matrix.Zero();
  38899. _this._tempMatrix = BABYLON.Matrix.Zero();
  38900. return _this;
  38901. }
  38902. TargetCamera.prototype.getFrontPosition = function (distance) {
  38903. this.getWorldMatrix();
  38904. var direction = this.getTarget().subtract(this.position);
  38905. direction.normalize();
  38906. direction.scaleInPlace(distance);
  38907. return this.globalPosition.add(direction);
  38908. };
  38909. TargetCamera.prototype._getLockedTargetPosition = function () {
  38910. if (!this.lockedTarget) {
  38911. return null;
  38912. }
  38913. if (this.lockedTarget.absolutePosition) {
  38914. this.lockedTarget.computeWorldMatrix();
  38915. }
  38916. return this.lockedTarget.absolutePosition || this.lockedTarget;
  38917. };
  38918. TargetCamera.prototype.storeState = function () {
  38919. this._storedPosition = this.position.clone();
  38920. this._storedRotation = this.rotation.clone();
  38921. if (this.rotationQuaternion) {
  38922. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  38923. }
  38924. return _super.prototype.storeState.call(this);
  38925. };
  38926. /**
  38927. * Restored camera state. You must call storeState() first
  38928. */
  38929. TargetCamera.prototype._restoreStateValues = function () {
  38930. if (!_super.prototype._restoreStateValues.call(this)) {
  38931. return false;
  38932. }
  38933. this.position = this._storedPosition.clone();
  38934. this.rotation = this._storedRotation.clone();
  38935. if (this.rotationQuaternion) {
  38936. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  38937. }
  38938. this.cameraDirection.copyFromFloats(0, 0, 0);
  38939. this.cameraRotation.copyFromFloats(0, 0);
  38940. return true;
  38941. };
  38942. // Cache
  38943. TargetCamera.prototype._initCache = function () {
  38944. _super.prototype._initCache.call(this);
  38945. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38946. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38947. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38948. };
  38949. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  38950. if (!ignoreParentClass) {
  38951. _super.prototype._updateCache.call(this);
  38952. }
  38953. var lockedTargetPosition = this._getLockedTargetPosition();
  38954. if (!lockedTargetPosition) {
  38955. this._cache.lockedTarget = null;
  38956. }
  38957. else {
  38958. if (!this._cache.lockedTarget) {
  38959. this._cache.lockedTarget = lockedTargetPosition.clone();
  38960. }
  38961. else {
  38962. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  38963. }
  38964. }
  38965. this._cache.rotation.copyFrom(this.rotation);
  38966. if (this.rotationQuaternion)
  38967. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  38968. };
  38969. // Synchronized
  38970. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  38971. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  38972. return false;
  38973. }
  38974. var lockedTargetPosition = this._getLockedTargetPosition();
  38975. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  38976. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  38977. };
  38978. // Methods
  38979. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  38980. var engine = this.getEngine();
  38981. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  38982. };
  38983. // Target
  38984. TargetCamera.prototype.setTarget = function (target) {
  38985. this.upVector.normalize();
  38986. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  38987. this._camMatrix.invert();
  38988. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  38989. var vDir = target.subtract(this.position);
  38990. if (vDir.x >= 0.0) {
  38991. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  38992. }
  38993. else {
  38994. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  38995. }
  38996. this.rotation.z = 0;
  38997. if (isNaN(this.rotation.x)) {
  38998. this.rotation.x = 0;
  38999. }
  39000. if (isNaN(this.rotation.y)) {
  39001. this.rotation.y = 0;
  39002. }
  39003. if (isNaN(this.rotation.z)) {
  39004. this.rotation.z = 0;
  39005. }
  39006. if (this.rotationQuaternion) {
  39007. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  39008. }
  39009. };
  39010. /**
  39011. * Return the current target position of the camera. This value is expressed in local space.
  39012. */
  39013. TargetCamera.prototype.getTarget = function () {
  39014. return this._currentTarget;
  39015. };
  39016. TargetCamera.prototype._decideIfNeedsToMove = function () {
  39017. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  39018. };
  39019. TargetCamera.prototype._updatePosition = function () {
  39020. if (this.parent) {
  39021. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  39022. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  39023. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  39024. return;
  39025. }
  39026. this.position.addInPlace(this.cameraDirection);
  39027. };
  39028. TargetCamera.prototype._checkInputs = function () {
  39029. var needToMove = this._decideIfNeedsToMove();
  39030. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  39031. // Move
  39032. if (needToMove) {
  39033. this._updatePosition();
  39034. }
  39035. // Rotate
  39036. if (needToRotate) {
  39037. this.rotation.x += this.cameraRotation.x;
  39038. this.rotation.y += this.cameraRotation.y;
  39039. //rotate, if quaternion is set and rotation was used
  39040. if (this.rotationQuaternion) {
  39041. var len = this.rotation.lengthSquared();
  39042. if (len) {
  39043. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  39044. }
  39045. }
  39046. if (!this.noRotationConstraint) {
  39047. var limit = (Math.PI / 2) * 0.95;
  39048. if (this.rotation.x > limit)
  39049. this.rotation.x = limit;
  39050. if (this.rotation.x < -limit)
  39051. this.rotation.x = -limit;
  39052. }
  39053. }
  39054. // Inertia
  39055. if (needToMove) {
  39056. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  39057. this.cameraDirection.x = 0;
  39058. }
  39059. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  39060. this.cameraDirection.y = 0;
  39061. }
  39062. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  39063. this.cameraDirection.z = 0;
  39064. }
  39065. this.cameraDirection.scaleInPlace(this.inertia);
  39066. }
  39067. if (needToRotate) {
  39068. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  39069. this.cameraRotation.x = 0;
  39070. }
  39071. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  39072. this.cameraRotation.y = 0;
  39073. }
  39074. this.cameraRotation.scaleInPlace(this.inertia);
  39075. }
  39076. _super.prototype._checkInputs.call(this);
  39077. };
  39078. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  39079. if (this.rotationQuaternion) {
  39080. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  39081. }
  39082. else {
  39083. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  39084. }
  39085. //update the up vector!
  39086. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  39087. };
  39088. TargetCamera.prototype._getViewMatrix = function () {
  39089. if (this.lockedTarget) {
  39090. this.setTarget(this._getLockedTargetPosition());
  39091. }
  39092. // Compute
  39093. this._updateCameraRotationMatrix();
  39094. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  39095. // Computing target and final matrix
  39096. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  39097. if (this.getScene().useRightHandedSystem) {
  39098. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  39099. }
  39100. else {
  39101. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  39102. }
  39103. return this._viewMatrix;
  39104. };
  39105. /**
  39106. * @override
  39107. * Override Camera.createRigCamera
  39108. */
  39109. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  39110. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  39111. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  39112. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  39113. if (!this.rotationQuaternion) {
  39114. this.rotationQuaternion = new BABYLON.Quaternion();
  39115. }
  39116. rigCamera._cameraRigParams = {};
  39117. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  39118. }
  39119. return rigCamera;
  39120. }
  39121. return null;
  39122. };
  39123. /**
  39124. * @override
  39125. * Override Camera._updateRigCameras
  39126. */
  39127. TargetCamera.prototype._updateRigCameras = function () {
  39128. var camLeft = this._rigCameras[0];
  39129. var camRight = this._rigCameras[1];
  39130. switch (this.cameraRigMode) {
  39131. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  39132. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  39133. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  39134. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  39135. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  39136. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  39137. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  39138. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  39139. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  39140. camLeft.setTarget(this.getTarget());
  39141. camRight.setTarget(this.getTarget());
  39142. break;
  39143. case BABYLON.Camera.RIG_MODE_VR:
  39144. if (camLeft.rotationQuaternion) {
  39145. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  39146. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  39147. }
  39148. else {
  39149. camLeft.rotation.copyFrom(this.rotation);
  39150. camRight.rotation.copyFrom(this.rotation);
  39151. }
  39152. camLeft.position.copyFrom(this.position);
  39153. camRight.position.copyFrom(this.position);
  39154. break;
  39155. }
  39156. _super.prototype._updateRigCameras.call(this);
  39157. };
  39158. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  39159. if (!this._rigCamTransformMatrix) {
  39160. this._rigCamTransformMatrix = new BABYLON.Matrix();
  39161. }
  39162. var target = this.getTarget();
  39163. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  39164. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  39165. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  39166. };
  39167. TargetCamera.prototype.getClassName = function () {
  39168. return "TargetCamera";
  39169. };
  39170. __decorate([
  39171. BABYLON.serializeAsVector3()
  39172. ], TargetCamera.prototype, "rotation", void 0);
  39173. __decorate([
  39174. BABYLON.serialize()
  39175. ], TargetCamera.prototype, "speed", void 0);
  39176. __decorate([
  39177. BABYLON.serializeAsMeshReference("lockedTargetId")
  39178. ], TargetCamera.prototype, "lockedTarget", void 0);
  39179. return TargetCamera;
  39180. }(BABYLON.Camera));
  39181. BABYLON.TargetCamera = TargetCamera;
  39182. })(BABYLON || (BABYLON = {}));
  39183. //# sourceMappingURL=babylon.targetCamera.js.map
  39184. var BABYLON;
  39185. (function (BABYLON) {
  39186. var FreeCamera = /** @class */ (function (_super) {
  39187. __extends(FreeCamera, _super);
  39188. function FreeCamera(name, position, scene) {
  39189. var _this = _super.call(this, name, position, scene) || this;
  39190. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  39191. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  39192. _this.checkCollisions = false;
  39193. _this.applyGravity = false;
  39194. _this._needMoveForGravity = false;
  39195. _this._oldPosition = BABYLON.Vector3.Zero();
  39196. _this._diffPosition = BABYLON.Vector3.Zero();
  39197. _this._newPosition = BABYLON.Vector3.Zero();
  39198. // Collisions
  39199. _this._collisionMask = -1;
  39200. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  39201. if (collidedMesh === void 0) { collidedMesh = null; }
  39202. //TODO move this to the collision coordinator!
  39203. if (_this.getScene().workerCollisions)
  39204. newPosition.multiplyInPlace(_this._collider._radius);
  39205. var updatePosition = function (newPos) {
  39206. _this._newPosition.copyFrom(newPos);
  39207. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  39208. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  39209. _this.position.addInPlace(_this._diffPosition);
  39210. if (_this.onCollide && collidedMesh) {
  39211. _this.onCollide(collidedMesh);
  39212. }
  39213. }
  39214. };
  39215. updatePosition(newPosition);
  39216. };
  39217. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  39218. _this.inputs.addKeyboard().addMouse();
  39219. return _this;
  39220. }
  39221. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  39222. //-- begin properties for backward compatibility for inputs
  39223. get: function () {
  39224. var mouse = this.inputs.attached["mouse"];
  39225. if (mouse)
  39226. return mouse.angularSensibility;
  39227. return 0;
  39228. },
  39229. set: function (value) {
  39230. var mouse = this.inputs.attached["mouse"];
  39231. if (mouse)
  39232. mouse.angularSensibility = value;
  39233. },
  39234. enumerable: true,
  39235. configurable: true
  39236. });
  39237. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  39238. get: function () {
  39239. var keyboard = this.inputs.attached["keyboard"];
  39240. if (keyboard)
  39241. return keyboard.keysUp;
  39242. return [];
  39243. },
  39244. set: function (value) {
  39245. var keyboard = this.inputs.attached["keyboard"];
  39246. if (keyboard)
  39247. keyboard.keysUp = value;
  39248. },
  39249. enumerable: true,
  39250. configurable: true
  39251. });
  39252. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  39253. get: function () {
  39254. var keyboard = this.inputs.attached["keyboard"];
  39255. if (keyboard)
  39256. return keyboard.keysDown;
  39257. return [];
  39258. },
  39259. set: function (value) {
  39260. var keyboard = this.inputs.attached["keyboard"];
  39261. if (keyboard)
  39262. keyboard.keysDown = value;
  39263. },
  39264. enumerable: true,
  39265. configurable: true
  39266. });
  39267. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  39268. get: function () {
  39269. var keyboard = this.inputs.attached["keyboard"];
  39270. if (keyboard)
  39271. return keyboard.keysLeft;
  39272. return [];
  39273. },
  39274. set: function (value) {
  39275. var keyboard = this.inputs.attached["keyboard"];
  39276. if (keyboard)
  39277. keyboard.keysLeft = value;
  39278. },
  39279. enumerable: true,
  39280. configurable: true
  39281. });
  39282. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  39283. get: function () {
  39284. var keyboard = this.inputs.attached["keyboard"];
  39285. if (keyboard)
  39286. return keyboard.keysRight;
  39287. return [];
  39288. },
  39289. set: function (value) {
  39290. var keyboard = this.inputs.attached["keyboard"];
  39291. if (keyboard)
  39292. keyboard.keysRight = value;
  39293. },
  39294. enumerable: true,
  39295. configurable: true
  39296. });
  39297. // Controls
  39298. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  39299. this.inputs.attachElement(element, noPreventDefault);
  39300. };
  39301. FreeCamera.prototype.detachControl = function (element) {
  39302. this.inputs.detachElement(element);
  39303. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  39304. this.cameraRotation = new BABYLON.Vector2(0, 0);
  39305. };
  39306. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  39307. get: function () {
  39308. return this._collisionMask;
  39309. },
  39310. set: function (mask) {
  39311. this._collisionMask = !isNaN(mask) ? mask : -1;
  39312. },
  39313. enumerable: true,
  39314. configurable: true
  39315. });
  39316. FreeCamera.prototype._collideWithWorld = function (displacement) {
  39317. var globalPosition;
  39318. if (this.parent) {
  39319. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  39320. }
  39321. else {
  39322. globalPosition = this.position;
  39323. }
  39324. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  39325. this._oldPosition.addInPlace(this.ellipsoidOffset);
  39326. if (!this._collider) {
  39327. this._collider = new BABYLON.Collider();
  39328. }
  39329. this._collider._radius = this.ellipsoid;
  39330. this._collider.collisionMask = this._collisionMask;
  39331. //no need for clone, as long as gravity is not on.
  39332. var actualDisplacement = displacement;
  39333. //add gravity to the direction to prevent the dual-collision checking
  39334. if (this.applyGravity) {
  39335. //this prevents mending with cameraDirection, a global variable of the free camera class.
  39336. actualDisplacement = displacement.add(this.getScene().gravity);
  39337. }
  39338. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  39339. };
  39340. FreeCamera.prototype._checkInputs = function () {
  39341. if (!this._localDirection) {
  39342. this._localDirection = BABYLON.Vector3.Zero();
  39343. this._transformedDirection = BABYLON.Vector3.Zero();
  39344. }
  39345. this.inputs.checkInputs();
  39346. _super.prototype._checkInputs.call(this);
  39347. };
  39348. FreeCamera.prototype._decideIfNeedsToMove = function () {
  39349. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  39350. };
  39351. FreeCamera.prototype._updatePosition = function () {
  39352. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  39353. this._collideWithWorld(this.cameraDirection);
  39354. }
  39355. else {
  39356. _super.prototype._updatePosition.call(this);
  39357. }
  39358. };
  39359. FreeCamera.prototype.dispose = function () {
  39360. this.inputs.clear();
  39361. _super.prototype.dispose.call(this);
  39362. };
  39363. FreeCamera.prototype.getClassName = function () {
  39364. return "FreeCamera";
  39365. };
  39366. __decorate([
  39367. BABYLON.serializeAsVector3()
  39368. ], FreeCamera.prototype, "ellipsoid", void 0);
  39369. __decorate([
  39370. BABYLON.serializeAsVector3()
  39371. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  39372. __decorate([
  39373. BABYLON.serialize()
  39374. ], FreeCamera.prototype, "checkCollisions", void 0);
  39375. __decorate([
  39376. BABYLON.serialize()
  39377. ], FreeCamera.prototype, "applyGravity", void 0);
  39378. return FreeCamera;
  39379. }(BABYLON.TargetCamera));
  39380. BABYLON.FreeCamera = FreeCamera;
  39381. })(BABYLON || (BABYLON = {}));
  39382. //# sourceMappingURL=babylon.freeCamera.js.map
  39383. var BABYLON;
  39384. (function (BABYLON) {
  39385. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  39386. function ArcRotateCameraKeyboardMoveInput() {
  39387. this._keys = new Array();
  39388. this.keysUp = [38];
  39389. this.keysDown = [40];
  39390. this.keysLeft = [37];
  39391. this.keysRight = [39];
  39392. this.keysReset = [220];
  39393. this.panningSensibility = 50.0;
  39394. this.zoomingSensibility = 25.0;
  39395. this.useAltToZoom = true;
  39396. }
  39397. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  39398. var _this = this;
  39399. if (this._onCanvasBlurObserver) {
  39400. return;
  39401. }
  39402. this._scene = this.camera.getScene();
  39403. this._engine = this._scene.getEngine();
  39404. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  39405. _this._keys = [];
  39406. });
  39407. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  39408. var evt = info.event;
  39409. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  39410. _this._ctrlPressed = evt.ctrlKey;
  39411. _this._altPressed = evt.altKey;
  39412. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  39413. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  39414. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  39415. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  39416. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  39417. var index = _this._keys.indexOf(evt.keyCode);
  39418. if (index === -1) {
  39419. _this._keys.push(evt.keyCode);
  39420. }
  39421. if (evt.preventDefault) {
  39422. if (!noPreventDefault) {
  39423. evt.preventDefault();
  39424. }
  39425. }
  39426. }
  39427. }
  39428. else {
  39429. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  39430. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  39431. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  39432. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  39433. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  39434. var index = _this._keys.indexOf(evt.keyCode);
  39435. if (index >= 0) {
  39436. _this._keys.splice(index, 1);
  39437. }
  39438. if (evt.preventDefault) {
  39439. if (!noPreventDefault) {
  39440. evt.preventDefault();
  39441. }
  39442. }
  39443. }
  39444. }
  39445. });
  39446. };
  39447. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  39448. if (this._scene) {
  39449. if (this._onKeyboardObserver) {
  39450. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  39451. }
  39452. if (this._onCanvasBlurObserver) {
  39453. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  39454. }
  39455. this._onKeyboardObserver = null;
  39456. this._onCanvasBlurObserver = null;
  39457. }
  39458. this._keys = [];
  39459. };
  39460. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  39461. if (this._onKeyboardObserver) {
  39462. var camera = this.camera;
  39463. for (var index = 0; index < this._keys.length; index++) {
  39464. var keyCode = this._keys[index];
  39465. if (this.keysLeft.indexOf(keyCode) !== -1) {
  39466. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39467. camera.inertialPanningX -= 1 / this.panningSensibility;
  39468. }
  39469. else {
  39470. camera.inertialAlphaOffset -= 0.01;
  39471. }
  39472. }
  39473. else if (this.keysUp.indexOf(keyCode) !== -1) {
  39474. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39475. camera.inertialPanningY += 1 / this.panningSensibility;
  39476. }
  39477. else if (this._altPressed && this.useAltToZoom) {
  39478. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  39479. }
  39480. else {
  39481. camera.inertialBetaOffset -= 0.01;
  39482. }
  39483. }
  39484. else if (this.keysRight.indexOf(keyCode) !== -1) {
  39485. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39486. camera.inertialPanningX += 1 / this.panningSensibility;
  39487. }
  39488. else {
  39489. camera.inertialAlphaOffset += 0.01;
  39490. }
  39491. }
  39492. else if (this.keysDown.indexOf(keyCode) !== -1) {
  39493. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39494. camera.inertialPanningY -= 1 / this.panningSensibility;
  39495. }
  39496. else if (this._altPressed && this.useAltToZoom) {
  39497. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  39498. }
  39499. else {
  39500. camera.inertialBetaOffset += 0.01;
  39501. }
  39502. }
  39503. else if (this.keysReset.indexOf(keyCode) !== -1) {
  39504. camera.restoreState();
  39505. }
  39506. }
  39507. }
  39508. };
  39509. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  39510. return "ArcRotateCameraKeyboardMoveInput";
  39511. };
  39512. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  39513. return "keyboard";
  39514. };
  39515. __decorate([
  39516. BABYLON.serialize()
  39517. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  39518. __decorate([
  39519. BABYLON.serialize()
  39520. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  39521. __decorate([
  39522. BABYLON.serialize()
  39523. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  39524. __decorate([
  39525. BABYLON.serialize()
  39526. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  39527. __decorate([
  39528. BABYLON.serialize()
  39529. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  39530. __decorate([
  39531. BABYLON.serialize()
  39532. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  39533. __decorate([
  39534. BABYLON.serialize()
  39535. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  39536. __decorate([
  39537. BABYLON.serialize()
  39538. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  39539. return ArcRotateCameraKeyboardMoveInput;
  39540. }());
  39541. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  39542. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  39543. })(BABYLON || (BABYLON = {}));
  39544. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  39545. var BABYLON;
  39546. (function (BABYLON) {
  39547. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  39548. function ArcRotateCameraMouseWheelInput() {
  39549. this.wheelPrecision = 3.0;
  39550. /**
  39551. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  39552. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  39553. */
  39554. this.wheelDeltaPercentage = 0;
  39555. }
  39556. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  39557. var _this = this;
  39558. this._wheel = function (p, s) {
  39559. //sanity check - this should be a PointerWheel event.
  39560. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  39561. return;
  39562. var event = p.event;
  39563. var delta = 0;
  39564. if (event.wheelDelta) {
  39565. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  39566. }
  39567. else if (event.detail) {
  39568. delta = -event.detail / _this.wheelPrecision;
  39569. }
  39570. if (delta)
  39571. _this.camera.inertialRadiusOffset += delta;
  39572. if (event.preventDefault) {
  39573. if (!noPreventDefault) {
  39574. event.preventDefault();
  39575. }
  39576. }
  39577. };
  39578. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  39579. };
  39580. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  39581. if (this._observer && element) {
  39582. this.camera.getScene().onPointerObservable.remove(this._observer);
  39583. this._observer = null;
  39584. this._wheel = null;
  39585. }
  39586. };
  39587. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  39588. return "ArcRotateCameraMouseWheelInput";
  39589. };
  39590. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  39591. return "mousewheel";
  39592. };
  39593. __decorate([
  39594. BABYLON.serialize()
  39595. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  39596. __decorate([
  39597. BABYLON.serialize()
  39598. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  39599. return ArcRotateCameraMouseWheelInput;
  39600. }());
  39601. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  39602. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  39603. })(BABYLON || (BABYLON = {}));
  39604. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  39605. var BABYLON;
  39606. (function (BABYLON) {
  39607. var ArcRotateCameraPointersInput = /** @class */ (function () {
  39608. function ArcRotateCameraPointersInput() {
  39609. this.buttons = [0, 1, 2];
  39610. this.angularSensibilityX = 1000.0;
  39611. this.angularSensibilityY = 1000.0;
  39612. this.pinchPrecision = 12.0;
  39613. /**
  39614. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  39615. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  39616. */
  39617. this.pinchDeltaPercentage = 0;
  39618. this.panningSensibility = 1000.0;
  39619. this.multiTouchPanning = true;
  39620. this.multiTouchPanAndZoom = true;
  39621. this._isPanClick = false;
  39622. this.pinchInwards = true;
  39623. }
  39624. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  39625. var _this = this;
  39626. var engine = this.camera.getEngine();
  39627. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  39628. var pointA = null;
  39629. var pointB = null;
  39630. var previousPinchSquaredDistance = 0;
  39631. var initialDistance = 0;
  39632. var twoFingerActivityCount = 0;
  39633. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  39634. this._pointerInput = function (p, s) {
  39635. var evt = p.event;
  39636. var isTouch = p.event.pointerType === "touch";
  39637. if (engine.isInVRExclusivePointerMode) {
  39638. return;
  39639. }
  39640. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  39641. return;
  39642. }
  39643. var srcElement = (evt.srcElement || evt.target);
  39644. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  39645. try {
  39646. srcElement.setPointerCapture(evt.pointerId);
  39647. }
  39648. catch (e) {
  39649. //Nothing to do with the error. Execution will continue.
  39650. }
  39651. // Manage panning with pan button click
  39652. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  39653. // manage pointers
  39654. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  39655. if (pointA === null) {
  39656. pointA = cacheSoloPointer;
  39657. }
  39658. else if (pointB === null) {
  39659. pointB = cacheSoloPointer;
  39660. }
  39661. if (!noPreventDefault) {
  39662. evt.preventDefault();
  39663. element.focus();
  39664. }
  39665. }
  39666. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  39667. _this.camera.restoreState();
  39668. }
  39669. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  39670. try {
  39671. srcElement.releasePointerCapture(evt.pointerId);
  39672. }
  39673. catch (e) {
  39674. //Nothing to do with the error.
  39675. }
  39676. cacheSoloPointer = null;
  39677. previousPinchSquaredDistance = 0;
  39678. previousMultiTouchPanPosition.isPaning = false;
  39679. previousMultiTouchPanPosition.isPinching = false;
  39680. twoFingerActivityCount = 0;
  39681. initialDistance = 0;
  39682. if (!isTouch) {
  39683. pointB = null; // Mouse and pen are mono pointer
  39684. }
  39685. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  39686. //but emptying completly pointers collection is required to fix a bug on iPhone :
  39687. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  39688. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  39689. if (engine.badOS) {
  39690. pointA = pointB = null;
  39691. }
  39692. else {
  39693. //only remove the impacted pointer in case of multitouch allowing on most
  39694. //platforms switching from rotate to zoom and pan seamlessly.
  39695. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  39696. pointA = pointB;
  39697. pointB = null;
  39698. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  39699. }
  39700. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  39701. pointB = null;
  39702. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  39703. }
  39704. else {
  39705. pointA = pointB = null;
  39706. }
  39707. }
  39708. if (!noPreventDefault) {
  39709. evt.preventDefault();
  39710. }
  39711. }
  39712. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  39713. if (!noPreventDefault) {
  39714. evt.preventDefault();
  39715. }
  39716. // One button down
  39717. if (pointA && pointB === null && cacheSoloPointer) {
  39718. if (_this.panningSensibility !== 0 &&
  39719. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  39720. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  39721. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  39722. }
  39723. else {
  39724. var offsetX = evt.clientX - cacheSoloPointer.x;
  39725. var offsetY = evt.clientY - cacheSoloPointer.y;
  39726. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  39727. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  39728. }
  39729. cacheSoloPointer.x = evt.clientX;
  39730. cacheSoloPointer.y = evt.clientY;
  39731. }
  39732. else if (pointA && pointB) {
  39733. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  39734. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  39735. ed.x = evt.clientX;
  39736. ed.y = evt.clientY;
  39737. var direction = _this.pinchInwards ? 1 : -1;
  39738. var distX = pointA.x - pointB.x;
  39739. var distY = pointA.y - pointB.y;
  39740. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  39741. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  39742. if (previousPinchSquaredDistance === 0) {
  39743. initialDistance = pinchDistance;
  39744. previousPinchSquaredDistance = pinchSquaredDistance;
  39745. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  39746. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  39747. return;
  39748. }
  39749. if (_this.multiTouchPanAndZoom) {
  39750. if (_this.pinchDeltaPercentage) {
  39751. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  39752. }
  39753. else {
  39754. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  39755. (_this.pinchPrecision *
  39756. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  39757. direction);
  39758. }
  39759. if (_this.panningSensibility !== 0) {
  39760. var pointersCenterX = (pointA.x + pointB.x) / 2;
  39761. var pointersCenterY = (pointA.y + pointB.y) / 2;
  39762. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  39763. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  39764. previousMultiTouchPanPosition.x = pointersCenterX;
  39765. previousMultiTouchPanPosition.y = pointersCenterY;
  39766. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  39767. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  39768. }
  39769. }
  39770. else {
  39771. twoFingerActivityCount++;
  39772. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  39773. if (_this.pinchDeltaPercentage) {
  39774. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  39775. }
  39776. else {
  39777. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  39778. (_this.pinchPrecision *
  39779. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  39780. direction);
  39781. }
  39782. previousMultiTouchPanPosition.isPaning = false;
  39783. previousMultiTouchPanPosition.isPinching = true;
  39784. }
  39785. else {
  39786. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  39787. if (!previousMultiTouchPanPosition.isPaning) {
  39788. previousMultiTouchPanPosition.isPaning = true;
  39789. previousMultiTouchPanPosition.isPinching = false;
  39790. previousMultiTouchPanPosition.x = ed.x;
  39791. previousMultiTouchPanPosition.y = ed.y;
  39792. return;
  39793. }
  39794. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  39795. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  39796. }
  39797. }
  39798. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  39799. previousMultiTouchPanPosition.x = ed.x;
  39800. previousMultiTouchPanPosition.y = ed.y;
  39801. }
  39802. }
  39803. previousPinchSquaredDistance = pinchSquaredDistance;
  39804. }
  39805. }
  39806. };
  39807. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  39808. this._onContextMenu = function (evt) {
  39809. evt.preventDefault();
  39810. };
  39811. if (!this.camera._useCtrlForPanning) {
  39812. element.addEventListener("contextmenu", this._onContextMenu, false);
  39813. }
  39814. this._onLostFocus = function () {
  39815. //this._keys = [];
  39816. pointA = pointB = null;
  39817. previousPinchSquaredDistance = 0;
  39818. previousMultiTouchPanPosition.isPaning = false;
  39819. previousMultiTouchPanPosition.isPinching = false;
  39820. twoFingerActivityCount = 0;
  39821. cacheSoloPointer = null;
  39822. initialDistance = 0;
  39823. };
  39824. this._onMouseMove = function (evt) {
  39825. if (!engine.isPointerLock) {
  39826. return;
  39827. }
  39828. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  39829. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  39830. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  39831. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  39832. if (!noPreventDefault) {
  39833. evt.preventDefault();
  39834. }
  39835. };
  39836. this._onGestureStart = function (e) {
  39837. if (window.MSGesture === undefined) {
  39838. return;
  39839. }
  39840. if (!_this._MSGestureHandler) {
  39841. _this._MSGestureHandler = new MSGesture();
  39842. _this._MSGestureHandler.target = element;
  39843. }
  39844. _this._MSGestureHandler.addPointer(e.pointerId);
  39845. };
  39846. this._onGesture = function (e) {
  39847. _this.camera.radius *= e.scale;
  39848. if (e.preventDefault) {
  39849. if (!noPreventDefault) {
  39850. e.stopPropagation();
  39851. e.preventDefault();
  39852. }
  39853. }
  39854. };
  39855. element.addEventListener("mousemove", this._onMouseMove, false);
  39856. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  39857. element.addEventListener("MSGestureChange", this._onGesture, false);
  39858. BABYLON.Tools.RegisterTopRootEvents([
  39859. { name: "blur", handler: this._onLostFocus }
  39860. ]);
  39861. };
  39862. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  39863. if (this._onLostFocus) {
  39864. BABYLON.Tools.UnregisterTopRootEvents([
  39865. { name: "blur", handler: this._onLostFocus }
  39866. ]);
  39867. }
  39868. if (element && this._observer) {
  39869. this.camera.getScene().onPointerObservable.remove(this._observer);
  39870. this._observer = null;
  39871. if (this._onContextMenu) {
  39872. element.removeEventListener("contextmenu", this._onContextMenu);
  39873. }
  39874. if (this._onMouseMove) {
  39875. element.removeEventListener("mousemove", this._onMouseMove);
  39876. }
  39877. if (this._onGestureStart) {
  39878. element.removeEventListener("MSPointerDown", this._onGestureStart);
  39879. }
  39880. if (this._onGesture) {
  39881. element.removeEventListener("MSGestureChange", this._onGesture);
  39882. }
  39883. this._isPanClick = false;
  39884. this.pinchInwards = true;
  39885. this._onMouseMove = null;
  39886. this._onGestureStart = null;
  39887. this._onGesture = null;
  39888. this._MSGestureHandler = null;
  39889. this._onLostFocus = null;
  39890. this._onContextMenu = null;
  39891. }
  39892. };
  39893. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  39894. return "ArcRotateCameraPointersInput";
  39895. };
  39896. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  39897. return "pointers";
  39898. };
  39899. __decorate([
  39900. BABYLON.serialize()
  39901. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  39902. __decorate([
  39903. BABYLON.serialize()
  39904. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  39905. __decorate([
  39906. BABYLON.serialize()
  39907. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  39908. __decorate([
  39909. BABYLON.serialize()
  39910. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  39911. __decorate([
  39912. BABYLON.serialize()
  39913. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  39914. __decorate([
  39915. BABYLON.serialize()
  39916. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  39917. __decorate([
  39918. BABYLON.serialize()
  39919. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  39920. __decorate([
  39921. BABYLON.serialize()
  39922. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  39923. return ArcRotateCameraPointersInput;
  39924. }());
  39925. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  39926. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  39927. })(BABYLON || (BABYLON = {}));
  39928. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  39929. var BABYLON;
  39930. (function (BABYLON) {
  39931. var ArcRotateCamera = /** @class */ (function (_super) {
  39932. __extends(ArcRotateCamera, _super);
  39933. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  39934. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  39935. _this.inertialAlphaOffset = 0;
  39936. _this.inertialBetaOffset = 0;
  39937. _this.inertialRadiusOffset = 0;
  39938. _this.lowerAlphaLimit = null;
  39939. _this.upperAlphaLimit = null;
  39940. _this.lowerBetaLimit = 0.01;
  39941. _this.upperBetaLimit = Math.PI;
  39942. _this.lowerRadiusLimit = null;
  39943. _this.upperRadiusLimit = null;
  39944. _this.inertialPanningX = 0;
  39945. _this.inertialPanningY = 0;
  39946. _this.pinchToPanMaxDistance = 20;
  39947. _this.panningDistanceLimit = null;
  39948. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  39949. _this.panningInertia = 0.9;
  39950. //-- end properties for backward compatibility for inputs
  39951. _this.zoomOnFactor = 1;
  39952. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  39953. _this.allowUpsideDown = true;
  39954. _this._viewMatrix = new BABYLON.Matrix();
  39955. // Panning
  39956. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  39957. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  39958. _this.checkCollisions = false;
  39959. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  39960. _this._previousPosition = BABYLON.Vector3.Zero();
  39961. _this._collisionVelocity = BABYLON.Vector3.Zero();
  39962. _this._newPosition = BABYLON.Vector3.Zero();
  39963. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  39964. if (collidedMesh === void 0) { collidedMesh = null; }
  39965. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  39966. newPosition.multiplyInPlace(_this._collider._radius);
  39967. }
  39968. if (!collidedMesh) {
  39969. _this._previousPosition.copyFrom(_this.position);
  39970. }
  39971. else {
  39972. _this.setPosition(newPosition);
  39973. if (_this.onCollide) {
  39974. _this.onCollide(collidedMesh);
  39975. }
  39976. }
  39977. // Recompute because of constraints
  39978. var cosa = Math.cos(_this.alpha);
  39979. var sina = Math.sin(_this.alpha);
  39980. var cosb = Math.cos(_this.beta);
  39981. var sinb = Math.sin(_this.beta);
  39982. if (sinb === 0) {
  39983. sinb = 0.0001;
  39984. }
  39985. var target = _this._getTargetPosition();
  39986. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  39987. _this.position.copyFrom(_this._newPosition);
  39988. var up = _this.upVector;
  39989. if (_this.allowUpsideDown && _this.beta < 0) {
  39990. up = up.clone();
  39991. up = up.negate();
  39992. }
  39993. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  39994. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  39995. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  39996. _this._collisionTriggered = false;
  39997. };
  39998. _this._target = BABYLON.Vector3.Zero();
  39999. if (target) {
  40000. _this.setTarget(target);
  40001. }
  40002. _this.alpha = alpha;
  40003. _this.beta = beta;
  40004. _this.radius = radius;
  40005. _this.getViewMatrix();
  40006. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  40007. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  40008. return _this;
  40009. }
  40010. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  40011. get: function () {
  40012. return this._target;
  40013. },
  40014. set: function (value) {
  40015. this.setTarget(value);
  40016. },
  40017. enumerable: true,
  40018. configurable: true
  40019. });
  40020. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  40021. //-- begin properties for backward compatibility for inputs
  40022. get: function () {
  40023. var pointers = this.inputs.attached["pointers"];
  40024. if (pointers)
  40025. return pointers.angularSensibilityX;
  40026. return 0;
  40027. },
  40028. set: function (value) {
  40029. var pointers = this.inputs.attached["pointers"];
  40030. if (pointers) {
  40031. pointers.angularSensibilityX = value;
  40032. }
  40033. },
  40034. enumerable: true,
  40035. configurable: true
  40036. });
  40037. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  40038. get: function () {
  40039. var pointers = this.inputs.attached["pointers"];
  40040. if (pointers)
  40041. return pointers.angularSensibilityY;
  40042. return 0;
  40043. },
  40044. set: function (value) {
  40045. var pointers = this.inputs.attached["pointers"];
  40046. if (pointers) {
  40047. pointers.angularSensibilityY = value;
  40048. }
  40049. },
  40050. enumerable: true,
  40051. configurable: true
  40052. });
  40053. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  40054. get: function () {
  40055. var pointers = this.inputs.attached["pointers"];
  40056. if (pointers)
  40057. return pointers.pinchPrecision;
  40058. return 0;
  40059. },
  40060. set: function (value) {
  40061. var pointers = this.inputs.attached["pointers"];
  40062. if (pointers) {
  40063. pointers.pinchPrecision = value;
  40064. }
  40065. },
  40066. enumerable: true,
  40067. configurable: true
  40068. });
  40069. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  40070. get: function () {
  40071. var pointers = this.inputs.attached["pointers"];
  40072. if (pointers)
  40073. return pointers.pinchDeltaPercentage;
  40074. return 0;
  40075. },
  40076. set: function (value) {
  40077. var pointers = this.inputs.attached["pointers"];
  40078. if (pointers) {
  40079. pointers.pinchDeltaPercentage = value;
  40080. }
  40081. },
  40082. enumerable: true,
  40083. configurable: true
  40084. });
  40085. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  40086. get: function () {
  40087. var pointers = this.inputs.attached["pointers"];
  40088. if (pointers)
  40089. return pointers.panningSensibility;
  40090. return 0;
  40091. },
  40092. set: function (value) {
  40093. var pointers = this.inputs.attached["pointers"];
  40094. if (pointers) {
  40095. pointers.panningSensibility = value;
  40096. }
  40097. },
  40098. enumerable: true,
  40099. configurable: true
  40100. });
  40101. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  40102. get: function () {
  40103. var keyboard = this.inputs.attached["keyboard"];
  40104. if (keyboard)
  40105. return keyboard.keysUp;
  40106. return [];
  40107. },
  40108. set: function (value) {
  40109. var keyboard = this.inputs.attached["keyboard"];
  40110. if (keyboard)
  40111. keyboard.keysUp = value;
  40112. },
  40113. enumerable: true,
  40114. configurable: true
  40115. });
  40116. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  40117. get: function () {
  40118. var keyboard = this.inputs.attached["keyboard"];
  40119. if (keyboard)
  40120. return keyboard.keysDown;
  40121. return [];
  40122. },
  40123. set: function (value) {
  40124. var keyboard = this.inputs.attached["keyboard"];
  40125. if (keyboard)
  40126. keyboard.keysDown = value;
  40127. },
  40128. enumerable: true,
  40129. configurable: true
  40130. });
  40131. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  40132. get: function () {
  40133. var keyboard = this.inputs.attached["keyboard"];
  40134. if (keyboard)
  40135. return keyboard.keysLeft;
  40136. return [];
  40137. },
  40138. set: function (value) {
  40139. var keyboard = this.inputs.attached["keyboard"];
  40140. if (keyboard)
  40141. keyboard.keysLeft = value;
  40142. },
  40143. enumerable: true,
  40144. configurable: true
  40145. });
  40146. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  40147. get: function () {
  40148. var keyboard = this.inputs.attached["keyboard"];
  40149. if (keyboard)
  40150. return keyboard.keysRight;
  40151. return [];
  40152. },
  40153. set: function (value) {
  40154. var keyboard = this.inputs.attached["keyboard"];
  40155. if (keyboard)
  40156. keyboard.keysRight = value;
  40157. },
  40158. enumerable: true,
  40159. configurable: true
  40160. });
  40161. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  40162. get: function () {
  40163. var mousewheel = this.inputs.attached["mousewheel"];
  40164. if (mousewheel)
  40165. return mousewheel.wheelPrecision;
  40166. return 0;
  40167. },
  40168. set: function (value) {
  40169. var mousewheel = this.inputs.attached["mousewheel"];
  40170. if (mousewheel)
  40171. mousewheel.wheelPrecision = value;
  40172. },
  40173. enumerable: true,
  40174. configurable: true
  40175. });
  40176. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  40177. get: function () {
  40178. var mousewheel = this.inputs.attached["mousewheel"];
  40179. if (mousewheel)
  40180. return mousewheel.wheelDeltaPercentage;
  40181. return 0;
  40182. },
  40183. set: function (value) {
  40184. var mousewheel = this.inputs.attached["mousewheel"];
  40185. if (mousewheel)
  40186. mousewheel.wheelDeltaPercentage = value;
  40187. },
  40188. enumerable: true,
  40189. configurable: true
  40190. });
  40191. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  40192. get: function () {
  40193. return this._bouncingBehavior;
  40194. },
  40195. enumerable: true,
  40196. configurable: true
  40197. });
  40198. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  40199. get: function () {
  40200. return this._bouncingBehavior != null;
  40201. },
  40202. set: function (value) {
  40203. if (value === this.useBouncingBehavior) {
  40204. return;
  40205. }
  40206. if (value) {
  40207. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  40208. this.addBehavior(this._bouncingBehavior);
  40209. }
  40210. else if (this._bouncingBehavior) {
  40211. this.removeBehavior(this._bouncingBehavior);
  40212. this._bouncingBehavior = null;
  40213. }
  40214. },
  40215. enumerable: true,
  40216. configurable: true
  40217. });
  40218. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  40219. get: function () {
  40220. return this._framingBehavior;
  40221. },
  40222. enumerable: true,
  40223. configurable: true
  40224. });
  40225. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  40226. get: function () {
  40227. return this._framingBehavior != null;
  40228. },
  40229. set: function (value) {
  40230. if (value === this.useFramingBehavior) {
  40231. return;
  40232. }
  40233. if (value) {
  40234. this._framingBehavior = new BABYLON.FramingBehavior();
  40235. this.addBehavior(this._framingBehavior);
  40236. }
  40237. else if (this._framingBehavior) {
  40238. this.removeBehavior(this._framingBehavior);
  40239. this._framingBehavior = null;
  40240. }
  40241. },
  40242. enumerable: true,
  40243. configurable: true
  40244. });
  40245. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  40246. get: function () {
  40247. return this._autoRotationBehavior;
  40248. },
  40249. enumerable: true,
  40250. configurable: true
  40251. });
  40252. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  40253. get: function () {
  40254. return this._autoRotationBehavior != null;
  40255. },
  40256. set: function (value) {
  40257. if (value === this.useAutoRotationBehavior) {
  40258. return;
  40259. }
  40260. if (value) {
  40261. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  40262. this.addBehavior(this._autoRotationBehavior);
  40263. }
  40264. else if (this._autoRotationBehavior) {
  40265. this.removeBehavior(this._autoRotationBehavior);
  40266. this._autoRotationBehavior = null;
  40267. }
  40268. },
  40269. enumerable: true,
  40270. configurable: true
  40271. });
  40272. // Cache
  40273. ArcRotateCamera.prototype._initCache = function () {
  40274. _super.prototype._initCache.call(this);
  40275. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  40276. this._cache.alpha = undefined;
  40277. this._cache.beta = undefined;
  40278. this._cache.radius = undefined;
  40279. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  40280. };
  40281. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  40282. if (!ignoreParentClass) {
  40283. _super.prototype._updateCache.call(this);
  40284. }
  40285. this._cache._target.copyFrom(this._getTargetPosition());
  40286. this._cache.alpha = this.alpha;
  40287. this._cache.beta = this.beta;
  40288. this._cache.radius = this.radius;
  40289. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  40290. };
  40291. ArcRotateCamera.prototype._getTargetPosition = function () {
  40292. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  40293. var pos = this._targetHost.getAbsolutePosition();
  40294. if (this._targetBoundingCenter) {
  40295. pos.addToRef(this._targetBoundingCenter, this._target);
  40296. }
  40297. else {
  40298. this._target.copyFrom(pos);
  40299. }
  40300. }
  40301. var lockedTargetPosition = this._getLockedTargetPosition();
  40302. if (lockedTargetPosition) {
  40303. return lockedTargetPosition;
  40304. }
  40305. return this._target;
  40306. };
  40307. ArcRotateCamera.prototype.storeState = function () {
  40308. this._storedAlpha = this.alpha;
  40309. this._storedBeta = this.beta;
  40310. this._storedRadius = this.radius;
  40311. this._storedTarget = this._getTargetPosition().clone();
  40312. return _super.prototype.storeState.call(this);
  40313. };
  40314. /**
  40315. * Restored camera state. You must call storeState() first
  40316. */
  40317. ArcRotateCamera.prototype._restoreStateValues = function () {
  40318. if (!_super.prototype._restoreStateValues.call(this)) {
  40319. return false;
  40320. }
  40321. this.alpha = this._storedAlpha;
  40322. this.beta = this._storedBeta;
  40323. this.radius = this._storedRadius;
  40324. this.setTarget(this._storedTarget.clone());
  40325. this.inertialAlphaOffset = 0;
  40326. this.inertialBetaOffset = 0;
  40327. this.inertialRadiusOffset = 0;
  40328. this.inertialPanningX = 0;
  40329. this.inertialPanningY = 0;
  40330. return true;
  40331. };
  40332. // Synchronized
  40333. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  40334. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  40335. return false;
  40336. return this._cache._target.equals(this._getTargetPosition())
  40337. && this._cache.alpha === this.alpha
  40338. && this._cache.beta === this.beta
  40339. && this._cache.radius === this.radius
  40340. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  40341. };
  40342. // Methods
  40343. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  40344. var _this = this;
  40345. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  40346. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  40347. this._useCtrlForPanning = useCtrlForPanning;
  40348. this._panningMouseButton = panningMouseButton;
  40349. this.inputs.attachElement(element, noPreventDefault);
  40350. this._reset = function () {
  40351. _this.inertialAlphaOffset = 0;
  40352. _this.inertialBetaOffset = 0;
  40353. _this.inertialRadiusOffset = 0;
  40354. _this.inertialPanningX = 0;
  40355. _this.inertialPanningY = 0;
  40356. };
  40357. };
  40358. ArcRotateCamera.prototype.detachControl = function (element) {
  40359. this.inputs.detachElement(element);
  40360. if (this._reset) {
  40361. this._reset();
  40362. }
  40363. };
  40364. ArcRotateCamera.prototype._checkInputs = function () {
  40365. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  40366. if (this._collisionTriggered) {
  40367. return;
  40368. }
  40369. this.inputs.checkInputs();
  40370. // Inertia
  40371. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  40372. if (this.getScene().useRightHandedSystem) {
  40373. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  40374. }
  40375. else {
  40376. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  40377. }
  40378. this.beta += this.inertialBetaOffset;
  40379. this.radius -= this.inertialRadiusOffset;
  40380. this.inertialAlphaOffset *= this.inertia;
  40381. this.inertialBetaOffset *= this.inertia;
  40382. this.inertialRadiusOffset *= this.inertia;
  40383. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  40384. this.inertialAlphaOffset = 0;
  40385. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  40386. this.inertialBetaOffset = 0;
  40387. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  40388. this.inertialRadiusOffset = 0;
  40389. }
  40390. // Panning inertia
  40391. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  40392. if (!this._localDirection) {
  40393. this._localDirection = BABYLON.Vector3.Zero();
  40394. this._transformedDirection = BABYLON.Vector3.Zero();
  40395. }
  40396. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  40397. this._localDirection.multiplyInPlace(this.panningAxis);
  40398. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  40399. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  40400. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  40401. if (!this.panningAxis.y) {
  40402. this._transformedDirection.y = 0;
  40403. }
  40404. if (!this._targetHost) {
  40405. if (this.panningDistanceLimit) {
  40406. this._transformedDirection.addInPlace(this._target);
  40407. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  40408. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  40409. this._target.copyFrom(this._transformedDirection);
  40410. }
  40411. }
  40412. else {
  40413. this._target.addInPlace(this._transformedDirection);
  40414. }
  40415. }
  40416. this.inertialPanningX *= this.panningInertia;
  40417. this.inertialPanningY *= this.panningInertia;
  40418. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  40419. this.inertialPanningX = 0;
  40420. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  40421. this.inertialPanningY = 0;
  40422. }
  40423. // Limits
  40424. this._checkLimits();
  40425. _super.prototype._checkInputs.call(this);
  40426. };
  40427. ArcRotateCamera.prototype._checkLimits = function () {
  40428. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  40429. if (this.allowUpsideDown && this.beta > Math.PI) {
  40430. this.beta = this.beta - (2 * Math.PI);
  40431. }
  40432. }
  40433. else {
  40434. if (this.beta < this.lowerBetaLimit) {
  40435. this.beta = this.lowerBetaLimit;
  40436. }
  40437. }
  40438. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  40439. if (this.allowUpsideDown && this.beta < -Math.PI) {
  40440. this.beta = this.beta + (2 * Math.PI);
  40441. }
  40442. }
  40443. else {
  40444. if (this.beta > this.upperBetaLimit) {
  40445. this.beta = this.upperBetaLimit;
  40446. }
  40447. }
  40448. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  40449. this.alpha = this.lowerAlphaLimit;
  40450. }
  40451. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  40452. this.alpha = this.upperAlphaLimit;
  40453. }
  40454. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  40455. this.radius = this.lowerRadiusLimit;
  40456. }
  40457. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  40458. this.radius = this.upperRadiusLimit;
  40459. }
  40460. };
  40461. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  40462. var radiusv3 = this.position.subtract(this._getTargetPosition());
  40463. this.radius = radiusv3.length();
  40464. if (this.radius === 0) {
  40465. this.radius = 0.0001; // Just to avoid division by zero
  40466. }
  40467. // Alpha
  40468. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  40469. if (radiusv3.z < 0) {
  40470. this.alpha = 2 * Math.PI - this.alpha;
  40471. }
  40472. // Beta
  40473. this.beta = Math.acos(radiusv3.y / this.radius);
  40474. this._checkLimits();
  40475. };
  40476. ArcRotateCamera.prototype.setPosition = function (position) {
  40477. if (this.position.equals(position)) {
  40478. return;
  40479. }
  40480. this.position.copyFrom(position);
  40481. this.rebuildAnglesAndRadius();
  40482. };
  40483. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  40484. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  40485. if (allowSamePosition === void 0) { allowSamePosition = false; }
  40486. if (target.getBoundingInfo) {
  40487. if (toBoundingCenter) {
  40488. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  40489. }
  40490. else {
  40491. this._targetBoundingCenter = null;
  40492. }
  40493. this._targetHost = target;
  40494. this._target = this._getTargetPosition();
  40495. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  40496. }
  40497. else {
  40498. var newTarget = target;
  40499. var currentTarget = this._getTargetPosition();
  40500. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  40501. return;
  40502. }
  40503. this._targetHost = null;
  40504. this._target = newTarget;
  40505. this._targetBoundingCenter = null;
  40506. this.onMeshTargetChangedObservable.notifyObservers(null);
  40507. }
  40508. this.rebuildAnglesAndRadius();
  40509. };
  40510. ArcRotateCamera.prototype._getViewMatrix = function () {
  40511. // Compute
  40512. var cosa = Math.cos(this.alpha);
  40513. var sina = Math.sin(this.alpha);
  40514. var cosb = Math.cos(this.beta);
  40515. var sinb = Math.sin(this.beta);
  40516. if (sinb === 0) {
  40517. sinb = 0.0001;
  40518. }
  40519. var target = this._getTargetPosition();
  40520. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  40521. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  40522. if (!this._collider) {
  40523. this._collider = new BABYLON.Collider();
  40524. }
  40525. this._collider._radius = this.collisionRadius;
  40526. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  40527. this._collisionTriggered = true;
  40528. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  40529. }
  40530. else {
  40531. this.position.copyFrom(this._newPosition);
  40532. var up = this.upVector;
  40533. if (this.allowUpsideDown && sinb < 0) {
  40534. up = up.clone();
  40535. up = up.negate();
  40536. }
  40537. if (this.getScene().useRightHandedSystem) {
  40538. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  40539. }
  40540. else {
  40541. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  40542. }
  40543. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  40544. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  40545. }
  40546. this._currentTarget = target;
  40547. return this._viewMatrix;
  40548. };
  40549. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  40550. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  40551. meshes = meshes || this.getScene().meshes;
  40552. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  40553. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  40554. this.radius = distance * this.zoomOnFactor;
  40555. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  40556. };
  40557. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  40558. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  40559. var meshesOrMinMaxVector;
  40560. var distance;
  40561. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  40562. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  40563. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  40564. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  40565. }
  40566. else {
  40567. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  40568. meshesOrMinMaxVector = minMaxVectorAndDistance;
  40569. distance = minMaxVectorAndDistance.distance;
  40570. }
  40571. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  40572. if (!doNotUpdateMaxZ) {
  40573. this.maxZ = distance * 2;
  40574. }
  40575. };
  40576. /**
  40577. * @override
  40578. * Override Camera.createRigCamera
  40579. */
  40580. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  40581. var alphaShift = 0;
  40582. switch (this.cameraRigMode) {
  40583. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  40584. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  40585. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  40586. case BABYLON.Camera.RIG_MODE_VR:
  40587. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  40588. break;
  40589. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  40590. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  40591. break;
  40592. }
  40593. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  40594. rigCam._cameraRigParams = {};
  40595. return rigCam;
  40596. };
  40597. /**
  40598. * @override
  40599. * Override Camera._updateRigCameras
  40600. */
  40601. ArcRotateCamera.prototype._updateRigCameras = function () {
  40602. var camLeft = this._rigCameras[0];
  40603. var camRight = this._rigCameras[1];
  40604. camLeft.beta = camRight.beta = this.beta;
  40605. camLeft.radius = camRight.radius = this.radius;
  40606. switch (this.cameraRigMode) {
  40607. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  40608. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  40609. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  40610. case BABYLON.Camera.RIG_MODE_VR:
  40611. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  40612. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  40613. break;
  40614. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  40615. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  40616. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  40617. break;
  40618. }
  40619. _super.prototype._updateRigCameras.call(this);
  40620. };
  40621. ArcRotateCamera.prototype.dispose = function () {
  40622. this.inputs.clear();
  40623. _super.prototype.dispose.call(this);
  40624. };
  40625. ArcRotateCamera.prototype.getClassName = function () {
  40626. return "ArcRotateCamera";
  40627. };
  40628. __decorate([
  40629. BABYLON.serialize()
  40630. ], ArcRotateCamera.prototype, "alpha", void 0);
  40631. __decorate([
  40632. BABYLON.serialize()
  40633. ], ArcRotateCamera.prototype, "beta", void 0);
  40634. __decorate([
  40635. BABYLON.serialize()
  40636. ], ArcRotateCamera.prototype, "radius", void 0);
  40637. __decorate([
  40638. BABYLON.serializeAsVector3("target")
  40639. ], ArcRotateCamera.prototype, "_target", void 0);
  40640. __decorate([
  40641. BABYLON.serialize()
  40642. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  40643. __decorate([
  40644. BABYLON.serialize()
  40645. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  40646. __decorate([
  40647. BABYLON.serialize()
  40648. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  40649. __decorate([
  40650. BABYLON.serialize()
  40651. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  40652. __decorate([
  40653. BABYLON.serialize()
  40654. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  40655. __decorate([
  40656. BABYLON.serialize()
  40657. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  40658. __decorate([
  40659. BABYLON.serialize()
  40660. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  40661. __decorate([
  40662. BABYLON.serialize()
  40663. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  40664. __decorate([
  40665. BABYLON.serialize()
  40666. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  40667. __decorate([
  40668. BABYLON.serialize()
  40669. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  40670. __decorate([
  40671. BABYLON.serialize()
  40672. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  40673. __decorate([
  40674. BABYLON.serialize()
  40675. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  40676. __decorate([
  40677. BABYLON.serialize()
  40678. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  40679. __decorate([
  40680. BABYLON.serializeAsVector3()
  40681. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  40682. __decorate([
  40683. BABYLON.serialize()
  40684. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  40685. __decorate([
  40686. BABYLON.serialize()
  40687. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  40688. __decorate([
  40689. BABYLON.serialize()
  40690. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  40691. return ArcRotateCamera;
  40692. }(BABYLON.TargetCamera));
  40693. BABYLON.ArcRotateCamera = ArcRotateCamera;
  40694. })(BABYLON || (BABYLON = {}));
  40695. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  40696. var BABYLON;
  40697. (function (BABYLON) {
  40698. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  40699. __extends(ArcRotateCameraInputsManager, _super);
  40700. function ArcRotateCameraInputsManager(camera) {
  40701. return _super.call(this, camera) || this;
  40702. }
  40703. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  40704. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  40705. return this;
  40706. };
  40707. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  40708. this.add(new BABYLON.ArcRotateCameraPointersInput());
  40709. return this;
  40710. };
  40711. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  40712. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  40713. return this;
  40714. };
  40715. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  40716. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  40717. return this;
  40718. };
  40719. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  40720. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  40721. return this;
  40722. };
  40723. return ArcRotateCameraInputsManager;
  40724. }(BABYLON.CameraInputsManager));
  40725. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  40726. })(BABYLON || (BABYLON = {}));
  40727. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  40728. var BABYLON;
  40729. (function (BABYLON) {
  40730. var HemisphericLight = /** @class */ (function (_super) {
  40731. __extends(HemisphericLight, _super);
  40732. /**
  40733. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  40734. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  40735. * The HemisphericLight can't cast shadows.
  40736. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40737. */
  40738. function HemisphericLight(name, direction, scene) {
  40739. var _this = _super.call(this, name, scene) || this;
  40740. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  40741. _this.direction = direction || BABYLON.Vector3.Up();
  40742. return _this;
  40743. }
  40744. HemisphericLight.prototype._buildUniformLayout = function () {
  40745. this._uniformBuffer.addUniform("vLightData", 4);
  40746. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40747. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40748. this._uniformBuffer.addUniform("vLightGround", 3);
  40749. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40750. this._uniformBuffer.addUniform("depthValues", 2);
  40751. this._uniformBuffer.create();
  40752. };
  40753. /**
  40754. * Returns the string "HemisphericLight".
  40755. */
  40756. HemisphericLight.prototype.getClassName = function () {
  40757. return "HemisphericLight";
  40758. };
  40759. /**
  40760. * Sets the HemisphericLight direction towards the passed target (Vector3).
  40761. * Returns the updated direction.
  40762. */
  40763. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  40764. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  40765. return this.direction;
  40766. };
  40767. HemisphericLight.prototype.getShadowGenerator = function () {
  40768. return null;
  40769. };
  40770. /**
  40771. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  40772. * Returns the HemisphericLight.
  40773. */
  40774. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  40775. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  40776. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  40777. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  40778. return this;
  40779. };
  40780. HemisphericLight.prototype._getWorldMatrix = function () {
  40781. if (!this._worldMatrix) {
  40782. this._worldMatrix = BABYLON.Matrix.Identity();
  40783. }
  40784. return this._worldMatrix;
  40785. };
  40786. /**
  40787. * Returns the integer 3.
  40788. */
  40789. HemisphericLight.prototype.getTypeID = function () {
  40790. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  40791. };
  40792. __decorate([
  40793. BABYLON.serializeAsColor3()
  40794. ], HemisphericLight.prototype, "groundColor", void 0);
  40795. __decorate([
  40796. BABYLON.serializeAsVector3()
  40797. ], HemisphericLight.prototype, "direction", void 0);
  40798. return HemisphericLight;
  40799. }(BABYLON.Light));
  40800. BABYLON.HemisphericLight = HemisphericLight;
  40801. })(BABYLON || (BABYLON = {}));
  40802. //# sourceMappingURL=babylon.hemisphericLight.js.map
  40803. var BABYLON;
  40804. (function (BABYLON) {
  40805. var ShadowLight = /** @class */ (function (_super) {
  40806. __extends(ShadowLight, _super);
  40807. function ShadowLight() {
  40808. var _this = _super !== null && _super.apply(this, arguments) || this;
  40809. _this._needProjectionMatrixCompute = true;
  40810. return _this;
  40811. }
  40812. Object.defineProperty(ShadowLight.prototype, "direction", {
  40813. get: function () {
  40814. return this._direction;
  40815. },
  40816. set: function (value) {
  40817. this._direction = value;
  40818. },
  40819. enumerable: true,
  40820. configurable: true
  40821. });
  40822. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  40823. get: function () {
  40824. return this._shadowMinZ;
  40825. },
  40826. set: function (value) {
  40827. this._shadowMinZ = value;
  40828. this.forceProjectionMatrixCompute();
  40829. },
  40830. enumerable: true,
  40831. configurable: true
  40832. });
  40833. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  40834. get: function () {
  40835. return this._shadowMaxZ;
  40836. },
  40837. set: function (value) {
  40838. this._shadowMaxZ = value;
  40839. this.forceProjectionMatrixCompute();
  40840. },
  40841. enumerable: true,
  40842. configurable: true
  40843. });
  40844. /**
  40845. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  40846. */
  40847. ShadowLight.prototype.computeTransformedInformation = function () {
  40848. if (this.parent && this.parent.getWorldMatrix) {
  40849. if (!this.transformedPosition) {
  40850. this.transformedPosition = BABYLON.Vector3.Zero();
  40851. }
  40852. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  40853. // In case the direction is present.
  40854. if (this.direction) {
  40855. if (!this.transformedDirection) {
  40856. this.transformedDirection = BABYLON.Vector3.Zero();
  40857. }
  40858. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  40859. }
  40860. return true;
  40861. }
  40862. return false;
  40863. };
  40864. /**
  40865. * Return the depth scale used for the shadow map.
  40866. */
  40867. ShadowLight.prototype.getDepthScale = function () {
  40868. return 50.0;
  40869. };
  40870. /**
  40871. * Returns the light direction (Vector3) for any passed face index.
  40872. */
  40873. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  40874. return this.transformedDirection ? this.transformedDirection : this.direction;
  40875. };
  40876. /**
  40877. * Returns the DirectionalLight absolute position in the World.
  40878. */
  40879. ShadowLight.prototype.getAbsolutePosition = function () {
  40880. return this.transformedPosition ? this.transformedPosition : this.position;
  40881. };
  40882. /**
  40883. * Sets the DirectionalLight direction toward the passed target (Vector3).
  40884. * Returns the updated DirectionalLight direction (Vector3).
  40885. */
  40886. ShadowLight.prototype.setDirectionToTarget = function (target) {
  40887. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  40888. return this.direction;
  40889. };
  40890. /**
  40891. * Returns the light rotation (Vector3).
  40892. */
  40893. ShadowLight.prototype.getRotation = function () {
  40894. this.direction.normalize();
  40895. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  40896. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  40897. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  40898. };
  40899. /**
  40900. * Boolean : false by default.
  40901. */
  40902. ShadowLight.prototype.needCube = function () {
  40903. return false;
  40904. };
  40905. /**
  40906. * Specifies wether or not the projection matrix should be recomputed this frame.
  40907. */
  40908. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  40909. return this._needProjectionMatrixCompute;
  40910. };
  40911. /**
  40912. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  40913. */
  40914. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  40915. this._needProjectionMatrixCompute = true;
  40916. };
  40917. /**
  40918. * Get the world matrix of the sahdow lights.
  40919. */
  40920. ShadowLight.prototype._getWorldMatrix = function () {
  40921. if (!this._worldMatrix) {
  40922. this._worldMatrix = BABYLON.Matrix.Identity();
  40923. }
  40924. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  40925. return this._worldMatrix;
  40926. };
  40927. /**
  40928. * Gets the minZ used for shadow according to both the scene and the light.
  40929. * @param activeCamera
  40930. */
  40931. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  40932. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  40933. };
  40934. /**
  40935. * Gets the maxZ used for shadow according to both the scene and the light.
  40936. * @param activeCamera
  40937. */
  40938. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  40939. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  40940. };
  40941. /**
  40942. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  40943. * Returns the light.
  40944. */
  40945. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40946. if (this.customProjectionMatrixBuilder) {
  40947. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  40948. }
  40949. else {
  40950. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  40951. }
  40952. return this;
  40953. };
  40954. __decorate([
  40955. BABYLON.serializeAsVector3()
  40956. ], ShadowLight.prototype, "position", void 0);
  40957. __decorate([
  40958. BABYLON.serializeAsVector3()
  40959. ], ShadowLight.prototype, "direction", null);
  40960. __decorate([
  40961. BABYLON.serialize()
  40962. ], ShadowLight.prototype, "shadowMinZ", null);
  40963. __decorate([
  40964. BABYLON.serialize()
  40965. ], ShadowLight.prototype, "shadowMaxZ", null);
  40966. return ShadowLight;
  40967. }(BABYLON.Light));
  40968. BABYLON.ShadowLight = ShadowLight;
  40969. })(BABYLON || (BABYLON = {}));
  40970. //# sourceMappingURL=babylon.shadowLight.js.map
  40971. var BABYLON;
  40972. (function (BABYLON) {
  40973. var PointLight = /** @class */ (function (_super) {
  40974. __extends(PointLight, _super);
  40975. /**
  40976. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  40977. * A PointLight emits the light in every direction.
  40978. * It can cast shadows.
  40979. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  40980. * ```javascript
  40981. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  40982. * ```
  40983. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40984. */
  40985. function PointLight(name, position, scene) {
  40986. var _this = _super.call(this, name, scene) || this;
  40987. _this._shadowAngle = Math.PI / 2;
  40988. _this.position = position;
  40989. return _this;
  40990. }
  40991. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  40992. /**
  40993. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  40994. * This specifies what angle the shadow will use to be created.
  40995. *
  40996. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  40997. */
  40998. get: function () {
  40999. return this._shadowAngle;
  41000. },
  41001. /**
  41002. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  41003. * This specifies what angle the shadow will use to be created.
  41004. *
  41005. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  41006. */
  41007. set: function (value) {
  41008. this._shadowAngle = value;
  41009. this.forceProjectionMatrixCompute();
  41010. },
  41011. enumerable: true,
  41012. configurable: true
  41013. });
  41014. Object.defineProperty(PointLight.prototype, "direction", {
  41015. get: function () {
  41016. return this._direction;
  41017. },
  41018. /**
  41019. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  41020. */
  41021. set: function (value) {
  41022. var previousNeedCube = this.needCube();
  41023. this._direction = value;
  41024. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  41025. this._shadowGenerator.recreateShadowMap();
  41026. }
  41027. },
  41028. enumerable: true,
  41029. configurable: true
  41030. });
  41031. /**
  41032. * Returns the string "PointLight"
  41033. */
  41034. PointLight.prototype.getClassName = function () {
  41035. return "PointLight";
  41036. };
  41037. /**
  41038. * Returns the integer 0.
  41039. */
  41040. PointLight.prototype.getTypeID = function () {
  41041. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  41042. };
  41043. /**
  41044. * Specifies wether or not the shadowmap should be a cube texture.
  41045. */
  41046. PointLight.prototype.needCube = function () {
  41047. return !this.direction;
  41048. };
  41049. /**
  41050. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  41051. */
  41052. PointLight.prototype.getShadowDirection = function (faceIndex) {
  41053. if (this.direction) {
  41054. return _super.prototype.getShadowDirection.call(this, faceIndex);
  41055. }
  41056. else {
  41057. switch (faceIndex) {
  41058. case 0:
  41059. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  41060. case 1:
  41061. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  41062. case 2:
  41063. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  41064. case 3:
  41065. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  41066. case 4:
  41067. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  41068. case 5:
  41069. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  41070. }
  41071. }
  41072. return BABYLON.Vector3.Zero();
  41073. };
  41074. /**
  41075. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  41076. * - fov = PI / 2
  41077. * - aspect ratio : 1.0
  41078. * - z-near and far equal to the active camera minZ and maxZ.
  41079. * Returns the PointLight.
  41080. */
  41081. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41082. var activeCamera = this.getScene().activeCamera;
  41083. if (!activeCamera) {
  41084. return;
  41085. }
  41086. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  41087. };
  41088. PointLight.prototype._buildUniformLayout = function () {
  41089. this._uniformBuffer.addUniform("vLightData", 4);
  41090. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  41091. this._uniformBuffer.addUniform("vLightSpecular", 3);
  41092. this._uniformBuffer.addUniform("shadowsInfo", 3);
  41093. this._uniformBuffer.addUniform("depthValues", 2);
  41094. this._uniformBuffer.create();
  41095. };
  41096. /**
  41097. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  41098. * Returns the PointLight.
  41099. */
  41100. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  41101. if (this.computeTransformedInformation()) {
  41102. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  41103. return this;
  41104. }
  41105. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  41106. return this;
  41107. };
  41108. __decorate([
  41109. BABYLON.serialize()
  41110. ], PointLight.prototype, "shadowAngle", null);
  41111. return PointLight;
  41112. }(BABYLON.ShadowLight));
  41113. BABYLON.PointLight = PointLight;
  41114. })(BABYLON || (BABYLON = {}));
  41115. //# sourceMappingURL=babylon.pointLight.js.map
  41116. var BABYLON;
  41117. (function (BABYLON) {
  41118. var DirectionalLight = /** @class */ (function (_super) {
  41119. __extends(DirectionalLight, _super);
  41120. /**
  41121. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  41122. * The directional light is emitted from everywhere in the given direction.
  41123. * It can cast shawdows.
  41124. * Documentation : http://doc.babylonjs.com/tutorials/lights
  41125. */
  41126. function DirectionalLight(name, direction, scene) {
  41127. var _this = _super.call(this, name, scene) || this;
  41128. _this._shadowFrustumSize = 0;
  41129. _this._shadowOrthoScale = 0.5;
  41130. _this.autoUpdateExtends = true;
  41131. // Cache
  41132. _this._orthoLeft = Number.MAX_VALUE;
  41133. _this._orthoRight = Number.MIN_VALUE;
  41134. _this._orthoTop = Number.MIN_VALUE;
  41135. _this._orthoBottom = Number.MAX_VALUE;
  41136. _this.position = direction.scale(-1.0);
  41137. _this.direction = direction;
  41138. return _this;
  41139. }
  41140. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  41141. /**
  41142. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  41143. */
  41144. get: function () {
  41145. return this._shadowFrustumSize;
  41146. },
  41147. /**
  41148. * Specifies a fix frustum size for the shadow generation.
  41149. */
  41150. set: function (value) {
  41151. this._shadowFrustumSize = value;
  41152. this.forceProjectionMatrixCompute();
  41153. },
  41154. enumerable: true,
  41155. configurable: true
  41156. });
  41157. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  41158. get: function () {
  41159. return this._shadowOrthoScale;
  41160. },
  41161. set: function (value) {
  41162. this._shadowOrthoScale = value;
  41163. this.forceProjectionMatrixCompute();
  41164. },
  41165. enumerable: true,
  41166. configurable: true
  41167. });
  41168. /**
  41169. * Returns the string "DirectionalLight".
  41170. */
  41171. DirectionalLight.prototype.getClassName = function () {
  41172. return "DirectionalLight";
  41173. };
  41174. /**
  41175. * Returns the integer 1.
  41176. */
  41177. DirectionalLight.prototype.getTypeID = function () {
  41178. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  41179. };
  41180. /**
  41181. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  41182. * Returns the DirectionalLight Shadow projection matrix.
  41183. */
  41184. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41185. if (this.shadowFrustumSize > 0) {
  41186. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  41187. }
  41188. else {
  41189. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  41190. }
  41191. };
  41192. /**
  41193. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  41194. * Returns the DirectionalLight Shadow projection matrix.
  41195. */
  41196. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  41197. var activeCamera = this.getScene().activeCamera;
  41198. if (!activeCamera) {
  41199. return;
  41200. }
  41201. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  41202. };
  41203. /**
  41204. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  41205. * Returns the DirectionalLight Shadow projection matrix.
  41206. */
  41207. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41208. var activeCamera = this.getScene().activeCamera;
  41209. if (!activeCamera) {
  41210. return;
  41211. }
  41212. // Check extends
  41213. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  41214. var tempVector3 = BABYLON.Vector3.Zero();
  41215. this._orthoLeft = Number.MAX_VALUE;
  41216. this._orthoRight = Number.MIN_VALUE;
  41217. this._orthoTop = Number.MIN_VALUE;
  41218. this._orthoBottom = Number.MAX_VALUE;
  41219. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  41220. var mesh = renderList[meshIndex];
  41221. if (!mesh) {
  41222. continue;
  41223. }
  41224. var boundingInfo = mesh.getBoundingInfo();
  41225. var boundingBox = boundingInfo.boundingBox;
  41226. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  41227. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  41228. if (tempVector3.x < this._orthoLeft)
  41229. this._orthoLeft = tempVector3.x;
  41230. if (tempVector3.y < this._orthoBottom)
  41231. this._orthoBottom = tempVector3.y;
  41232. if (tempVector3.x > this._orthoRight)
  41233. this._orthoRight = tempVector3.x;
  41234. if (tempVector3.y > this._orthoTop)
  41235. this._orthoTop = tempVector3.y;
  41236. }
  41237. }
  41238. }
  41239. var xOffset = this._orthoRight - this._orthoLeft;
  41240. var yOffset = this._orthoTop - this._orthoBottom;
  41241. 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);
  41242. };
  41243. DirectionalLight.prototype._buildUniformLayout = function () {
  41244. this._uniformBuffer.addUniform("vLightData", 4);
  41245. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  41246. this._uniformBuffer.addUniform("vLightSpecular", 3);
  41247. this._uniformBuffer.addUniform("shadowsInfo", 3);
  41248. this._uniformBuffer.addUniform("depthValues", 2);
  41249. this._uniformBuffer.create();
  41250. };
  41251. /**
  41252. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  41253. * Returns the DirectionalLight.
  41254. */
  41255. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  41256. if (this.computeTransformedInformation()) {
  41257. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  41258. return this;
  41259. }
  41260. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  41261. return this;
  41262. };
  41263. /**
  41264. * Gets the minZ used for shadow according to both the scene and the light.
  41265. *
  41266. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  41267. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  41268. * @param activeCamera
  41269. */
  41270. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  41271. return 1;
  41272. };
  41273. /**
  41274. * Gets the maxZ used for shadow according to both the scene and the light.
  41275. *
  41276. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  41277. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  41278. * @param activeCamera
  41279. */
  41280. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  41281. return 1;
  41282. };
  41283. __decorate([
  41284. BABYLON.serialize()
  41285. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  41286. __decorate([
  41287. BABYLON.serialize()
  41288. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  41289. __decorate([
  41290. BABYLON.serialize()
  41291. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  41292. return DirectionalLight;
  41293. }(BABYLON.ShadowLight));
  41294. BABYLON.DirectionalLight = DirectionalLight;
  41295. })(BABYLON || (BABYLON = {}));
  41296. //# sourceMappingURL=babylon.directionalLight.js.map
  41297. var BABYLON;
  41298. (function (BABYLON) {
  41299. var SpotLight = /** @class */ (function (_super) {
  41300. __extends(SpotLight, _super);
  41301. /**
  41302. * Creates a SpotLight object in the scene with the passed parameters :
  41303. * - `position` (Vector3) is the initial SpotLight position,
  41304. * - `direction` (Vector3) is the initial SpotLight direction,
  41305. * - `angle` (float, in radians) is the spot light cone angle,
  41306. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  41307. * A spot light is a simply light oriented cone.
  41308. * It can cast shadows.
  41309. * Documentation : http://doc.babylonjs.com/tutorials/lights
  41310. */
  41311. function SpotLight(name, position, direction, angle, exponent, scene) {
  41312. var _this = _super.call(this, name, scene) || this;
  41313. _this.position = position;
  41314. _this.direction = direction;
  41315. _this.angle = angle;
  41316. _this.exponent = exponent;
  41317. return _this;
  41318. }
  41319. Object.defineProperty(SpotLight.prototype, "angle", {
  41320. get: function () {
  41321. return this._angle;
  41322. },
  41323. set: function (value) {
  41324. this._angle = value;
  41325. this.forceProjectionMatrixCompute();
  41326. },
  41327. enumerable: true,
  41328. configurable: true
  41329. });
  41330. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  41331. get: function () {
  41332. return this._shadowAngleScale;
  41333. },
  41334. /**
  41335. * Allows scaling the angle of the light for shadow generation only.
  41336. */
  41337. set: function (value) {
  41338. this._shadowAngleScale = value;
  41339. this.forceProjectionMatrixCompute();
  41340. },
  41341. enumerable: true,
  41342. configurable: true
  41343. });
  41344. /**
  41345. * Returns the string "SpotLight".
  41346. */
  41347. SpotLight.prototype.getClassName = function () {
  41348. return "SpotLight";
  41349. };
  41350. /**
  41351. * Returns the integer 2.
  41352. */
  41353. SpotLight.prototype.getTypeID = function () {
  41354. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  41355. };
  41356. /**
  41357. * 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.
  41358. * Returns the SpotLight.
  41359. */
  41360. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41361. var activeCamera = this.getScene().activeCamera;
  41362. if (!activeCamera) {
  41363. return;
  41364. }
  41365. this._shadowAngleScale = this._shadowAngleScale || 1;
  41366. var angle = this._shadowAngleScale * this._angle;
  41367. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  41368. };
  41369. SpotLight.prototype._buildUniformLayout = function () {
  41370. this._uniformBuffer.addUniform("vLightData", 4);
  41371. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  41372. this._uniformBuffer.addUniform("vLightSpecular", 3);
  41373. this._uniformBuffer.addUniform("vLightDirection", 3);
  41374. this._uniformBuffer.addUniform("shadowsInfo", 3);
  41375. this._uniformBuffer.addUniform("depthValues", 2);
  41376. this._uniformBuffer.create();
  41377. };
  41378. /**
  41379. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  41380. * Return the SpotLight.
  41381. */
  41382. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  41383. var normalizeDirection;
  41384. if (this.computeTransformedInformation()) {
  41385. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  41386. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  41387. }
  41388. else {
  41389. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  41390. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  41391. }
  41392. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  41393. return this;
  41394. };
  41395. __decorate([
  41396. BABYLON.serialize()
  41397. ], SpotLight.prototype, "angle", null);
  41398. __decorate([
  41399. BABYLON.serialize()
  41400. /**
  41401. * Allows scaling the angle of the light for shadow generation only.
  41402. */
  41403. ], SpotLight.prototype, "shadowAngleScale", null);
  41404. __decorate([
  41405. BABYLON.serialize()
  41406. ], SpotLight.prototype, "exponent", void 0);
  41407. return SpotLight;
  41408. }(BABYLON.ShadowLight));
  41409. BABYLON.SpotLight = SpotLight;
  41410. })(BABYLON || (BABYLON = {}));
  41411. //# sourceMappingURL=babylon.spotLight.js.map
  41412. var BABYLON;
  41413. (function (BABYLON) {
  41414. var AnimationRange = /** @class */ (function () {
  41415. function AnimationRange(name, from, to) {
  41416. this.name = name;
  41417. this.from = from;
  41418. this.to = to;
  41419. }
  41420. AnimationRange.prototype.clone = function () {
  41421. return new AnimationRange(this.name, this.from, this.to);
  41422. };
  41423. return AnimationRange;
  41424. }());
  41425. BABYLON.AnimationRange = AnimationRange;
  41426. /**
  41427. * Composed of a frame, and an action function
  41428. */
  41429. var AnimationEvent = /** @class */ (function () {
  41430. function AnimationEvent(frame, action, onlyOnce) {
  41431. this.frame = frame;
  41432. this.action = action;
  41433. this.onlyOnce = onlyOnce;
  41434. this.isDone = false;
  41435. }
  41436. return AnimationEvent;
  41437. }());
  41438. BABYLON.AnimationEvent = AnimationEvent;
  41439. var PathCursor = /** @class */ (function () {
  41440. function PathCursor(path) {
  41441. this.path = path;
  41442. this._onchange = new Array();
  41443. this.value = 0;
  41444. this.animations = new Array();
  41445. }
  41446. PathCursor.prototype.getPoint = function () {
  41447. var point = this.path.getPointAtLengthPosition(this.value);
  41448. return new BABYLON.Vector3(point.x, 0, point.y);
  41449. };
  41450. PathCursor.prototype.moveAhead = function (step) {
  41451. if (step === void 0) { step = 0.002; }
  41452. this.move(step);
  41453. return this;
  41454. };
  41455. PathCursor.prototype.moveBack = function (step) {
  41456. if (step === void 0) { step = 0.002; }
  41457. this.move(-step);
  41458. return this;
  41459. };
  41460. PathCursor.prototype.move = function (step) {
  41461. if (Math.abs(step) > 1) {
  41462. throw "step size should be less than 1.";
  41463. }
  41464. this.value += step;
  41465. this.ensureLimits();
  41466. this.raiseOnChange();
  41467. return this;
  41468. };
  41469. PathCursor.prototype.ensureLimits = function () {
  41470. while (this.value > 1) {
  41471. this.value -= 1;
  41472. }
  41473. while (this.value < 0) {
  41474. this.value += 1;
  41475. }
  41476. return this;
  41477. };
  41478. // used by animation engine
  41479. PathCursor.prototype.raiseOnChange = function () {
  41480. var _this = this;
  41481. this._onchange.forEach(function (f) { return f(_this); });
  41482. return this;
  41483. };
  41484. PathCursor.prototype.onchange = function (f) {
  41485. this._onchange.push(f);
  41486. return this;
  41487. };
  41488. return PathCursor;
  41489. }());
  41490. BABYLON.PathCursor = PathCursor;
  41491. var Animation = /** @class */ (function () {
  41492. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  41493. this.name = name;
  41494. this.targetProperty = targetProperty;
  41495. this.framePerSecond = framePerSecond;
  41496. this.dataType = dataType;
  41497. this.loopMode = loopMode;
  41498. this.enableBlending = enableBlending;
  41499. this._runtimeAnimations = new Array();
  41500. // The set of event that will be linked to this animation
  41501. this._events = new Array();
  41502. this.blendingSpeed = 0.01;
  41503. this._ranges = {};
  41504. this.targetPropertyPath = targetProperty.split(".");
  41505. this.dataType = dataType;
  41506. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  41507. }
  41508. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  41509. var dataType = undefined;
  41510. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  41511. dataType = Animation.ANIMATIONTYPE_FLOAT;
  41512. }
  41513. else if (from instanceof BABYLON.Quaternion) {
  41514. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  41515. }
  41516. else if (from instanceof BABYLON.Vector3) {
  41517. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  41518. }
  41519. else if (from instanceof BABYLON.Vector2) {
  41520. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  41521. }
  41522. else if (from instanceof BABYLON.Color3) {
  41523. dataType = Animation.ANIMATIONTYPE_COLOR3;
  41524. }
  41525. else if (from instanceof BABYLON.Size) {
  41526. dataType = Animation.ANIMATIONTYPE_SIZE;
  41527. }
  41528. if (dataType == undefined) {
  41529. return null;
  41530. }
  41531. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  41532. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  41533. animation.setKeys(keys);
  41534. if (easingFunction !== undefined) {
  41535. animation.setEasingFunction(easingFunction);
  41536. }
  41537. return animation;
  41538. };
  41539. /**
  41540. * Sets up an animation.
  41541. * @param property the property to animate
  41542. * @param animationType the animation type to apply
  41543. * @param easingFunction the easing function used in the animation
  41544. * @returns The created animation
  41545. */
  41546. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  41547. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  41548. animation.setEasingFunction(easingFunction);
  41549. return animation;
  41550. };
  41551. /**
  41552. * Create and start an animation on a node
  41553. * @param {string} name defines the name of the global animation that will be run on all nodes
  41554. * @param {BABYLON.Node} node defines the root node where the animation will take place
  41555. * @param {string} targetProperty defines property to animate
  41556. * @param {number} framePerSecond defines the number of frame per second yo use
  41557. * @param {number} totalFrame defines the number of frames in total
  41558. * @param {any} from defines the initial value
  41559. * @param {any} to defines the final value
  41560. * @param {number} loopMode defines which loop mode you want to use (off by default)
  41561. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  41562. * @param onAnimationEnd defines the callback to call when animation end
  41563. * @returns the animatable created for this animation
  41564. */
  41565. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  41566. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  41567. if (!animation) {
  41568. return null;
  41569. }
  41570. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  41571. };
  41572. /**
  41573. * Create and start an animation on a node and its descendants
  41574. * @param {string} name defines the name of the global animation that will be run on all nodes
  41575. * @param {BABYLON.Node} node defines the root node where the animation will take place
  41576. * @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.
  41577. * @param {string} targetProperty defines property to animate
  41578. * @param {number} framePerSecond defines the number of frame per second yo use
  41579. * @param {number} totalFrame defines the number of frames in total
  41580. * @param {any} from defines the initial value
  41581. * @param {any} to defines the final value
  41582. * @param {number} loopMode defines which loop mode you want to use (off by default)
  41583. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  41584. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  41585. * @returns the list of animatables created for all nodes
  41586. * @example https://www.babylonjs-playground.com/#MH0VLI
  41587. */
  41588. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  41589. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  41590. if (!animation) {
  41591. return null;
  41592. }
  41593. var scene = node.getScene();
  41594. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  41595. };
  41596. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  41597. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  41598. if (!animation) {
  41599. return null;
  41600. }
  41601. node.animations.push(animation);
  41602. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  41603. };
  41604. /**
  41605. * Transition property of the Camera to the target Value.
  41606. * @param property The property to transition
  41607. * @param targetValue The target Value of the property
  41608. * @param host The object where the property to animate belongs
  41609. * @param scene Scene used to run the animation
  41610. * @param frameRate Framerate (in frame/s) to use
  41611. * @param transition The transition type we want to use
  41612. * @param duration The duration of the animation, in milliseconds
  41613. * @param onAnimationEnd Call back trigger at the end of the animation.
  41614. */
  41615. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  41616. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  41617. if (duration <= 0) {
  41618. host[property] = targetValue;
  41619. if (onAnimationEnd) {
  41620. onAnimationEnd();
  41621. }
  41622. return null;
  41623. }
  41624. var endFrame = frameRate * (duration / 1000);
  41625. transition.setKeys([{
  41626. frame: 0,
  41627. value: host[property].clone ? host[property].clone() : host[property]
  41628. },
  41629. {
  41630. frame: endFrame,
  41631. value: targetValue
  41632. }]);
  41633. if (!host.animations) {
  41634. host.animations = [];
  41635. }
  41636. host.animations.push(transition);
  41637. var animation = scene.beginAnimation(host, 0, endFrame, false);
  41638. animation.onAnimationEnd = onAnimationEnd;
  41639. return animation;
  41640. };
  41641. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  41642. /**
  41643. * Return the array of runtime animations currently using this animation
  41644. */
  41645. get: function () {
  41646. return this._runtimeAnimations;
  41647. },
  41648. enumerable: true,
  41649. configurable: true
  41650. });
  41651. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  41652. get: function () {
  41653. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  41654. var runtimeAnimation = _a[_i];
  41655. if (!runtimeAnimation.isStopped) {
  41656. return true;
  41657. }
  41658. }
  41659. return false;
  41660. },
  41661. enumerable: true,
  41662. configurable: true
  41663. });
  41664. // Methods
  41665. /**
  41666. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  41667. */
  41668. Animation.prototype.toString = function (fullDetails) {
  41669. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  41670. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  41671. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  41672. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  41673. if (fullDetails) {
  41674. ret += ", Ranges: {";
  41675. var first = true;
  41676. for (var name in this._ranges) {
  41677. if (first) {
  41678. ret += ", ";
  41679. first = false;
  41680. }
  41681. ret += name;
  41682. }
  41683. ret += "}";
  41684. }
  41685. return ret;
  41686. };
  41687. /**
  41688. * Add an event to this animation.
  41689. */
  41690. Animation.prototype.addEvent = function (event) {
  41691. this._events.push(event);
  41692. };
  41693. /**
  41694. * Remove all events found at the given frame
  41695. * @param frame
  41696. */
  41697. Animation.prototype.removeEvents = function (frame) {
  41698. for (var index = 0; index < this._events.length; index++) {
  41699. if (this._events[index].frame === frame) {
  41700. this._events.splice(index, 1);
  41701. index--;
  41702. }
  41703. }
  41704. };
  41705. Animation.prototype.getEvents = function () {
  41706. return this._events;
  41707. };
  41708. Animation.prototype.createRange = function (name, from, to) {
  41709. // check name not already in use; could happen for bones after serialized
  41710. if (!this._ranges[name]) {
  41711. this._ranges[name] = new AnimationRange(name, from, to);
  41712. }
  41713. };
  41714. Animation.prototype.deleteRange = function (name, deleteFrames) {
  41715. if (deleteFrames === void 0) { deleteFrames = true; }
  41716. var range = this._ranges[name];
  41717. if (!range) {
  41718. return;
  41719. }
  41720. if (deleteFrames) {
  41721. var from = range.from;
  41722. var to = range.to;
  41723. // this loop MUST go high to low for multiple splices to work
  41724. for (var key = this._keys.length - 1; key >= 0; key--) {
  41725. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  41726. this._keys.splice(key, 1);
  41727. }
  41728. }
  41729. }
  41730. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  41731. };
  41732. Animation.prototype.getRange = function (name) {
  41733. return this._ranges[name];
  41734. };
  41735. Animation.prototype.getKeys = function () {
  41736. return this._keys;
  41737. };
  41738. Animation.prototype.getHighestFrame = function () {
  41739. var ret = 0;
  41740. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  41741. if (ret < this._keys[key].frame) {
  41742. ret = this._keys[key].frame;
  41743. }
  41744. }
  41745. return ret;
  41746. };
  41747. Animation.prototype.getEasingFunction = function () {
  41748. return this._easingFunction;
  41749. };
  41750. Animation.prototype.setEasingFunction = function (easingFunction) {
  41751. this._easingFunction = easingFunction;
  41752. };
  41753. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  41754. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  41755. };
  41756. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  41757. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  41758. };
  41759. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  41760. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  41761. };
  41762. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  41763. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  41764. };
  41765. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  41766. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  41767. };
  41768. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  41769. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  41770. };
  41771. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  41772. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  41773. };
  41774. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  41775. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  41776. };
  41777. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  41778. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  41779. };
  41780. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  41781. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  41782. };
  41783. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  41784. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  41785. };
  41786. Animation.prototype.clone = function () {
  41787. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  41788. clone.enableBlending = this.enableBlending;
  41789. clone.blendingSpeed = this.blendingSpeed;
  41790. if (this._keys) {
  41791. clone.setKeys(this._keys);
  41792. }
  41793. if (this._ranges) {
  41794. clone._ranges = {};
  41795. for (var name in this._ranges) {
  41796. var range = this._ranges[name];
  41797. if (!range) {
  41798. continue;
  41799. }
  41800. clone._ranges[name] = range.clone();
  41801. }
  41802. }
  41803. return clone;
  41804. };
  41805. Animation.prototype.setKeys = function (values) {
  41806. this._keys = values.slice(0);
  41807. };
  41808. Animation.prototype.serialize = function () {
  41809. var serializationObject = {};
  41810. serializationObject.name = this.name;
  41811. serializationObject.property = this.targetProperty;
  41812. serializationObject.framePerSecond = this.framePerSecond;
  41813. serializationObject.dataType = this.dataType;
  41814. serializationObject.loopBehavior = this.loopMode;
  41815. serializationObject.enableBlending = this.enableBlending;
  41816. serializationObject.blendingSpeed = this.blendingSpeed;
  41817. var dataType = this.dataType;
  41818. serializationObject.keys = [];
  41819. var keys = this.getKeys();
  41820. for (var index = 0; index < keys.length; index++) {
  41821. var animationKey = keys[index];
  41822. var key = {};
  41823. key.frame = animationKey.frame;
  41824. switch (dataType) {
  41825. case Animation.ANIMATIONTYPE_FLOAT:
  41826. key.values = [animationKey.value];
  41827. break;
  41828. case Animation.ANIMATIONTYPE_QUATERNION:
  41829. case Animation.ANIMATIONTYPE_MATRIX:
  41830. case Animation.ANIMATIONTYPE_VECTOR3:
  41831. case Animation.ANIMATIONTYPE_COLOR3:
  41832. key.values = animationKey.value.asArray();
  41833. break;
  41834. }
  41835. serializationObject.keys.push(key);
  41836. }
  41837. serializationObject.ranges = [];
  41838. for (var name in this._ranges) {
  41839. var source = this._ranges[name];
  41840. if (!source) {
  41841. continue;
  41842. }
  41843. var range = {};
  41844. range.name = name;
  41845. range.from = source.from;
  41846. range.to = source.to;
  41847. serializationObject.ranges.push(range);
  41848. }
  41849. return serializationObject;
  41850. };
  41851. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  41852. get: function () {
  41853. return Animation._ANIMATIONTYPE_FLOAT;
  41854. },
  41855. enumerable: true,
  41856. configurable: true
  41857. });
  41858. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  41859. get: function () {
  41860. return Animation._ANIMATIONTYPE_VECTOR3;
  41861. },
  41862. enumerable: true,
  41863. configurable: true
  41864. });
  41865. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  41866. get: function () {
  41867. return Animation._ANIMATIONTYPE_VECTOR2;
  41868. },
  41869. enumerable: true,
  41870. configurable: true
  41871. });
  41872. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  41873. get: function () {
  41874. return Animation._ANIMATIONTYPE_SIZE;
  41875. },
  41876. enumerable: true,
  41877. configurable: true
  41878. });
  41879. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  41880. get: function () {
  41881. return Animation._ANIMATIONTYPE_QUATERNION;
  41882. },
  41883. enumerable: true,
  41884. configurable: true
  41885. });
  41886. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  41887. get: function () {
  41888. return Animation._ANIMATIONTYPE_MATRIX;
  41889. },
  41890. enumerable: true,
  41891. configurable: true
  41892. });
  41893. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  41894. get: function () {
  41895. return Animation._ANIMATIONTYPE_COLOR3;
  41896. },
  41897. enumerable: true,
  41898. configurable: true
  41899. });
  41900. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  41901. get: function () {
  41902. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  41903. },
  41904. enumerable: true,
  41905. configurable: true
  41906. });
  41907. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  41908. get: function () {
  41909. return Animation._ANIMATIONLOOPMODE_CYCLE;
  41910. },
  41911. enumerable: true,
  41912. configurable: true
  41913. });
  41914. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  41915. get: function () {
  41916. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  41917. },
  41918. enumerable: true,
  41919. configurable: true
  41920. });
  41921. Animation.Parse = function (parsedAnimation) {
  41922. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  41923. var dataType = parsedAnimation.dataType;
  41924. var keys = [];
  41925. var data;
  41926. var index;
  41927. if (parsedAnimation.enableBlending) {
  41928. animation.enableBlending = parsedAnimation.enableBlending;
  41929. }
  41930. if (parsedAnimation.blendingSpeed) {
  41931. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  41932. }
  41933. for (index = 0; index < parsedAnimation.keys.length; index++) {
  41934. var key = parsedAnimation.keys[index];
  41935. var inTangent;
  41936. var outTangent;
  41937. switch (dataType) {
  41938. case Animation.ANIMATIONTYPE_FLOAT:
  41939. data = key.values[0];
  41940. if (key.values.length >= 1) {
  41941. inTangent = key.values[1];
  41942. }
  41943. if (key.values.length >= 2) {
  41944. outTangent = key.values[2];
  41945. }
  41946. break;
  41947. case Animation.ANIMATIONTYPE_QUATERNION:
  41948. data = BABYLON.Quaternion.FromArray(key.values);
  41949. if (key.values.length >= 8) {
  41950. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  41951. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  41952. inTangent = _inTangent;
  41953. }
  41954. }
  41955. if (key.values.length >= 12) {
  41956. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  41957. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  41958. outTangent = _outTangent;
  41959. }
  41960. }
  41961. break;
  41962. case Animation.ANIMATIONTYPE_MATRIX:
  41963. data = BABYLON.Matrix.FromArray(key.values);
  41964. break;
  41965. case Animation.ANIMATIONTYPE_COLOR3:
  41966. data = BABYLON.Color3.FromArray(key.values);
  41967. break;
  41968. case Animation.ANIMATIONTYPE_VECTOR3:
  41969. default:
  41970. data = BABYLON.Vector3.FromArray(key.values);
  41971. break;
  41972. }
  41973. var keyData = {};
  41974. keyData.frame = key.frame;
  41975. keyData.value = data;
  41976. if (inTangent != undefined) {
  41977. keyData.inTangent = inTangent;
  41978. }
  41979. if (outTangent != undefined) {
  41980. keyData.outTangent = outTangent;
  41981. }
  41982. keys.push(keyData);
  41983. }
  41984. animation.setKeys(keys);
  41985. if (parsedAnimation.ranges) {
  41986. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  41987. data = parsedAnimation.ranges[index];
  41988. animation.createRange(data.name, data.from, data.to);
  41989. }
  41990. }
  41991. return animation;
  41992. };
  41993. Animation.AppendSerializedAnimations = function (source, destination) {
  41994. if (source.animations) {
  41995. destination.animations = [];
  41996. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  41997. var animation = source.animations[animationIndex];
  41998. destination.animations.push(animation.serialize());
  41999. }
  42000. }
  42001. };
  42002. Animation.AllowMatricesInterpolation = false;
  42003. // Statics
  42004. Animation._ANIMATIONTYPE_FLOAT = 0;
  42005. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  42006. Animation._ANIMATIONTYPE_QUATERNION = 2;
  42007. Animation._ANIMATIONTYPE_MATRIX = 3;
  42008. Animation._ANIMATIONTYPE_COLOR3 = 4;
  42009. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  42010. Animation._ANIMATIONTYPE_SIZE = 6;
  42011. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  42012. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  42013. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  42014. return Animation;
  42015. }());
  42016. BABYLON.Animation = Animation;
  42017. })(BABYLON || (BABYLON = {}));
  42018. //# sourceMappingURL=babylon.animation.js.map
  42019. var BABYLON;
  42020. (function (BABYLON) {
  42021. /**
  42022. * This class defines the direct association between an animation and a target
  42023. */
  42024. var TargetedAnimation = /** @class */ (function () {
  42025. function TargetedAnimation() {
  42026. }
  42027. return TargetedAnimation;
  42028. }());
  42029. BABYLON.TargetedAnimation = TargetedAnimation;
  42030. /**
  42031. * Use this class to create coordinated animations on multiple targets
  42032. */
  42033. var AnimationGroup = /** @class */ (function () {
  42034. function AnimationGroup(name, scene) {
  42035. if (scene === void 0) { scene = null; }
  42036. this.name = name;
  42037. this._targetedAnimations = new Array();
  42038. this._animatables = new Array();
  42039. this._from = Number.MAX_VALUE;
  42040. this._to = Number.MIN_VALUE;
  42041. this._speedRatio = 1;
  42042. this.onAnimationEndObservable = new BABYLON.Observable();
  42043. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  42044. this._scene.animationGroups.push(this);
  42045. }
  42046. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  42047. /**
  42048. * Define if the animations are started
  42049. */
  42050. get: function () {
  42051. return this._isStarted;
  42052. },
  42053. enumerable: true,
  42054. configurable: true
  42055. });
  42056. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  42057. /**
  42058. * Gets or sets the speed ratio to use for all animations
  42059. */
  42060. get: function () {
  42061. return this._speedRatio;
  42062. },
  42063. /**
  42064. * Gets or sets the speed ratio to use for all animations
  42065. */
  42066. set: function (value) {
  42067. if (this._speedRatio === value) {
  42068. return;
  42069. }
  42070. this._speedRatio = value;
  42071. for (var index = 0; index < this._animatables.length; index++) {
  42072. var animatable = this._animatables[index];
  42073. animatable.speedRatio = this._speedRatio;
  42074. }
  42075. },
  42076. enumerable: true,
  42077. configurable: true
  42078. });
  42079. /**
  42080. * Add an animation (with its target) in the group
  42081. * @param animation defines the animation we want to add
  42082. * @param target defines the target of the animation
  42083. * @returns the {BABYLON.TargetedAnimation} object
  42084. */
  42085. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  42086. var targetedAnimation = {
  42087. animation: animation,
  42088. target: target
  42089. };
  42090. var keys = animation.getKeys();
  42091. if (this._from > keys[0].frame) {
  42092. this._from = keys[0].frame;
  42093. }
  42094. if (this._to < keys[keys.length - 1].frame) {
  42095. this._to = keys[keys.length - 1].frame;
  42096. }
  42097. this._targetedAnimations.push(targetedAnimation);
  42098. return targetedAnimation;
  42099. };
  42100. /**
  42101. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  42102. * It can add constant keys at begin or end
  42103. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smaller begin frame of all animations
  42104. * @param endFrame defines the new end frame for all animations. It can't be smaller than the larger end frame of all animations
  42105. */
  42106. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  42107. beginFrame = Math.min(beginFrame, this._from);
  42108. endFrame = Math.min(endFrame, this._to);
  42109. for (var index = 0; index < this._targetedAnimations.length; index++) {
  42110. var targetedAnimation = this._targetedAnimations[index];
  42111. var keys = targetedAnimation.animation.getKeys();
  42112. var startKey = keys[0];
  42113. var endKey = keys[keys.length - 1];
  42114. if (startKey.frame > beginFrame) {
  42115. var newKey = {
  42116. frame: beginFrame,
  42117. value: startKey.value,
  42118. inTangent: startKey.inTangent,
  42119. outTangent: startKey.outTangent
  42120. };
  42121. keys.splice(0, 0, newKey);
  42122. }
  42123. if (endKey.frame < endFrame) {
  42124. var newKey = {
  42125. frame: endFrame,
  42126. value: endKey.value,
  42127. inTangent: startKey.outTangent,
  42128. outTangent: startKey.outTangent
  42129. };
  42130. keys.push(newKey);
  42131. }
  42132. }
  42133. return this;
  42134. };
  42135. /**
  42136. * Start all animations on given targets
  42137. * @param loop defines if animations must loop
  42138. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  42139. */
  42140. AnimationGroup.prototype.start = function (loop, speedRatio) {
  42141. var _this = this;
  42142. if (loop === void 0) { loop = false; }
  42143. if (speedRatio === void 0) { speedRatio = 1; }
  42144. if (this._isStarted || this._targetedAnimations.length === 0) {
  42145. return this;
  42146. }
  42147. var _loop_1 = function () {
  42148. var targetedAnimation = this_1._targetedAnimations[index];
  42149. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  42150. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  42151. }));
  42152. };
  42153. var this_1 = this;
  42154. for (var index = 0; index < this._targetedAnimations.length; index++) {
  42155. _loop_1();
  42156. }
  42157. this._speedRatio = speedRatio;
  42158. this._isStarted = true;
  42159. return this;
  42160. };
  42161. /**
  42162. * Pause all animations
  42163. */
  42164. AnimationGroup.prototype.pause = function () {
  42165. if (!this._isStarted) {
  42166. return this;
  42167. }
  42168. for (var index = 0; index < this._animatables.length; index++) {
  42169. var animatable = this._animatables[index];
  42170. animatable.pause();
  42171. }
  42172. return this;
  42173. };
  42174. /**
  42175. * Play all animations to initial state
  42176. * This function will start() the animations if they were not started or will restart() them if they were paused
  42177. * @param loop defines if animations must loop
  42178. */
  42179. AnimationGroup.prototype.play = function (loop) {
  42180. if (this.isStarted) {
  42181. if (loop !== undefined) {
  42182. for (var index = 0; index < this._animatables.length; index++) {
  42183. var animatable = this._animatables[index];
  42184. animatable.loopAnimation = loop;
  42185. }
  42186. }
  42187. this.restart();
  42188. }
  42189. else {
  42190. this.start(loop, this._speedRatio);
  42191. }
  42192. return this;
  42193. };
  42194. /**
  42195. * Reset all animations to initial state
  42196. */
  42197. AnimationGroup.prototype.reset = function () {
  42198. if (!this._isStarted) {
  42199. return this;
  42200. }
  42201. for (var index = 0; index < this._animatables.length; index++) {
  42202. var animatable = this._animatables[index];
  42203. animatable.reset();
  42204. }
  42205. return this;
  42206. };
  42207. /**
  42208. * Restart animations from key 0
  42209. */
  42210. AnimationGroup.prototype.restart = function () {
  42211. if (!this._isStarted) {
  42212. return this;
  42213. }
  42214. for (var index = 0; index < this._animatables.length; index++) {
  42215. var animatable = this._animatables[index];
  42216. animatable.restart();
  42217. }
  42218. return this;
  42219. };
  42220. /**
  42221. * Stop all animations
  42222. */
  42223. AnimationGroup.prototype.stop = function () {
  42224. if (!this._isStarted) {
  42225. return this;
  42226. }
  42227. for (var index = 0; index < this._animatables.length; index++) {
  42228. var animatable = this._animatables[index];
  42229. animatable.stop();
  42230. }
  42231. this._isStarted = false;
  42232. return this;
  42233. };
  42234. /**
  42235. * Dispose all associated resources
  42236. */
  42237. AnimationGroup.prototype.dispose = function () {
  42238. this._targetedAnimations = [];
  42239. this._animatables = [];
  42240. var index = this._scene.animationGroups.indexOf(this);
  42241. if (index > -1) {
  42242. this._scene.animationGroups.splice(index, 1);
  42243. }
  42244. };
  42245. return AnimationGroup;
  42246. }());
  42247. BABYLON.AnimationGroup = AnimationGroup;
  42248. })(BABYLON || (BABYLON = {}));
  42249. //# sourceMappingURL=babylon.animationGroup.js.map
  42250. var BABYLON;
  42251. (function (BABYLON) {
  42252. var RuntimeAnimation = /** @class */ (function () {
  42253. function RuntimeAnimation(target, animation) {
  42254. this._offsetsCache = {};
  42255. this._highLimitsCache = {};
  42256. this._stopped = false;
  42257. this._blendingFactor = 0;
  42258. this._ratioOffset = 0;
  42259. this._animation = animation;
  42260. this._target = target;
  42261. animation._runtimeAnimations.push(this);
  42262. }
  42263. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  42264. get: function () {
  42265. return this._animation;
  42266. },
  42267. enumerable: true,
  42268. configurable: true
  42269. });
  42270. RuntimeAnimation.prototype.reset = function () {
  42271. this._offsetsCache = {};
  42272. this._highLimitsCache = {};
  42273. this.currentFrame = 0;
  42274. this._blendingFactor = 0;
  42275. this._originalBlendValue = null;
  42276. };
  42277. RuntimeAnimation.prototype.isStopped = function () {
  42278. return this._stopped;
  42279. };
  42280. RuntimeAnimation.prototype.dispose = function () {
  42281. var index = this._animation.runtimeAnimations.indexOf(this);
  42282. if (index > -1) {
  42283. this._animation.runtimeAnimations.splice(index, 1);
  42284. }
  42285. };
  42286. RuntimeAnimation.prototype._getKeyValue = function (value) {
  42287. if (typeof value === "function") {
  42288. return value();
  42289. }
  42290. return value;
  42291. };
  42292. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  42293. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  42294. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  42295. }
  42296. this.currentFrame = currentFrame;
  42297. var keys = this._animation.getKeys();
  42298. // Try to get a hash to find the right key
  42299. 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));
  42300. if (keys[startKeyIndex].frame >= currentFrame) {
  42301. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  42302. startKeyIndex--;
  42303. }
  42304. }
  42305. for (var key = startKeyIndex; key < keys.length; key++) {
  42306. var endKey = keys[key + 1];
  42307. if (endKey.frame >= currentFrame) {
  42308. var startKey = keys[key];
  42309. var startValue = this._getKeyValue(startKey.value);
  42310. var endValue = this._getKeyValue(endKey.value);
  42311. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  42312. var frameDelta = endKey.frame - startKey.frame;
  42313. // gradient : percent of currentFrame between the frame inf and the frame sup
  42314. var gradient = (currentFrame - startKey.frame) / frameDelta;
  42315. // check for easingFunction and correction of gradient
  42316. var easingFunction = this._animation.getEasingFunction();
  42317. if (easingFunction != null) {
  42318. gradient = easingFunction.ease(gradient);
  42319. }
  42320. switch (this._animation.dataType) {
  42321. // Float
  42322. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  42323. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  42324. switch (loopMode) {
  42325. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42326. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42327. return floatValue;
  42328. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42329. return offsetValue * repeatCount + floatValue;
  42330. }
  42331. break;
  42332. // Quaternion
  42333. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  42334. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  42335. switch (loopMode) {
  42336. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42337. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42338. return quatValue;
  42339. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42340. return quatValue.add(offsetValue.scale(repeatCount));
  42341. }
  42342. return quatValue;
  42343. // Vector3
  42344. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  42345. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  42346. switch (loopMode) {
  42347. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42348. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42349. return vec3Value;
  42350. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42351. return vec3Value.add(offsetValue.scale(repeatCount));
  42352. }
  42353. // Vector2
  42354. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  42355. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  42356. switch (loopMode) {
  42357. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42358. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42359. return vec2Value;
  42360. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42361. return vec2Value.add(offsetValue.scale(repeatCount));
  42362. }
  42363. // Size
  42364. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  42365. switch (loopMode) {
  42366. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42367. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42368. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  42369. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42370. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  42371. }
  42372. // Color3
  42373. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  42374. switch (loopMode) {
  42375. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42376. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42377. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  42378. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42379. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  42380. }
  42381. // Matrix
  42382. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  42383. switch (loopMode) {
  42384. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42385. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42386. if (BABYLON.Animation.AllowMatricesInterpolation) {
  42387. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  42388. }
  42389. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42390. return startValue;
  42391. }
  42392. default:
  42393. break;
  42394. }
  42395. break;
  42396. }
  42397. }
  42398. return this._getKeyValue(keys[keys.length - 1].value);
  42399. };
  42400. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  42401. if (blend === void 0) { blend = false; }
  42402. // Set value
  42403. var path;
  42404. var destination;
  42405. var targetPropertyPath = this._animation.targetPropertyPath;
  42406. if (targetPropertyPath.length > 1) {
  42407. var property = this._target[targetPropertyPath[0]];
  42408. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  42409. property = property[targetPropertyPath[index]];
  42410. }
  42411. path = targetPropertyPath[targetPropertyPath.length - 1];
  42412. destination = property;
  42413. }
  42414. else {
  42415. path = targetPropertyPath[0];
  42416. destination = this._target;
  42417. }
  42418. // Blending
  42419. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  42420. if (!this._originalBlendValue) {
  42421. if (destination[path].clone) {
  42422. this._originalBlendValue = destination[path].clone();
  42423. }
  42424. else {
  42425. this._originalBlendValue = destination[path];
  42426. }
  42427. }
  42428. if (this._originalBlendValue.prototype) {
  42429. if (this._originalBlendValue.prototype.Lerp) {
  42430. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  42431. }
  42432. else {
  42433. destination[path] = currentValue;
  42434. }
  42435. }
  42436. else if (this._originalBlendValue.m) {
  42437. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  42438. }
  42439. else {
  42440. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  42441. }
  42442. this._blendingFactor += this._animation.blendingSpeed;
  42443. }
  42444. else {
  42445. destination[path] = currentValue;
  42446. }
  42447. if (this._target.markAsDirty) {
  42448. this._target.markAsDirty(this._animation.targetProperty);
  42449. }
  42450. };
  42451. RuntimeAnimation.prototype.goToFrame = function (frame) {
  42452. var keys = this._animation.getKeys();
  42453. if (frame < keys[0].frame) {
  42454. frame = keys[0].frame;
  42455. }
  42456. else if (frame > keys[keys.length - 1].frame) {
  42457. frame = keys[keys.length - 1].frame;
  42458. }
  42459. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  42460. this.setValue(currentValue);
  42461. };
  42462. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  42463. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  42464. this._ratioOffset = this._previousRatio - newRatio;
  42465. };
  42466. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  42467. if (blend === void 0) { blend = false; }
  42468. var targetPropertyPath = this._animation.targetPropertyPath;
  42469. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  42470. this._stopped = true;
  42471. return false;
  42472. }
  42473. var returnValue = true;
  42474. var keys = this._animation.getKeys();
  42475. // Adding a start key at frame 0 if missing
  42476. if (keys[0].frame !== 0) {
  42477. var newKey = { frame: 0, value: keys[0].value };
  42478. keys.splice(0, 0, newKey);
  42479. }
  42480. // Check limits
  42481. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  42482. from = keys[0].frame;
  42483. }
  42484. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  42485. to = keys[keys.length - 1].frame;
  42486. }
  42487. //to and from cannot be the same key
  42488. if (from === to) {
  42489. if (from > keys[0].frame) {
  42490. from--;
  42491. }
  42492. else if (to < keys[keys.length - 1].frame) {
  42493. to++;
  42494. }
  42495. }
  42496. // Compute ratio
  42497. var range = to - from;
  42498. var offsetValue;
  42499. // ratio represents the frame delta between from and to
  42500. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  42501. var highLimitValue = 0;
  42502. this._previousDelay = delay;
  42503. this._previousRatio = ratio;
  42504. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  42505. returnValue = false;
  42506. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  42507. }
  42508. else {
  42509. // Get max value if required
  42510. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  42511. var keyOffset = to.toString() + from.toString();
  42512. if (!this._offsetsCache[keyOffset]) {
  42513. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  42514. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  42515. switch (this._animation.dataType) {
  42516. // Float
  42517. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  42518. this._offsetsCache[keyOffset] = toValue - fromValue;
  42519. break;
  42520. // Quaternion
  42521. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  42522. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42523. break;
  42524. // Vector3
  42525. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  42526. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42527. // Vector2
  42528. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  42529. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42530. // Size
  42531. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  42532. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42533. // Color3
  42534. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  42535. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42536. default:
  42537. break;
  42538. }
  42539. this._highLimitsCache[keyOffset] = toValue;
  42540. }
  42541. highLimitValue = this._highLimitsCache[keyOffset];
  42542. offsetValue = this._offsetsCache[keyOffset];
  42543. }
  42544. }
  42545. if (offsetValue === undefined) {
  42546. switch (this._animation.dataType) {
  42547. // Float
  42548. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  42549. offsetValue = 0;
  42550. break;
  42551. // Quaternion
  42552. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  42553. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  42554. break;
  42555. // Vector3
  42556. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  42557. offsetValue = BABYLON.Vector3.Zero();
  42558. break;
  42559. // Vector2
  42560. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  42561. offsetValue = BABYLON.Vector2.Zero();
  42562. break;
  42563. // Size
  42564. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  42565. offsetValue = BABYLON.Size.Zero();
  42566. break;
  42567. // Color3
  42568. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  42569. offsetValue = BABYLON.Color3.Black();
  42570. }
  42571. }
  42572. // Compute value
  42573. var repeatCount = (ratio / range) >> 0;
  42574. var currentFrame = returnValue ? from + ratio % range : to;
  42575. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  42576. // Set value
  42577. this.setValue(currentValue);
  42578. // Check events
  42579. var events = this._animation.getEvents();
  42580. for (var index = 0; index < events.length; index++) {
  42581. // Make sure current frame has passed event frame and that event frame is within the current range
  42582. // Also, handle both forward and reverse animations
  42583. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  42584. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  42585. var event = events[index];
  42586. if (!event.isDone) {
  42587. // If event should be done only once, remove it.
  42588. if (event.onlyOnce) {
  42589. events.splice(index, 1);
  42590. index--;
  42591. }
  42592. event.isDone = true;
  42593. event.action();
  42594. } // Don't do anything if the event has already be done.
  42595. }
  42596. else if (events[index].isDone && !events[index].onlyOnce) {
  42597. // reset event, the animation is looping
  42598. events[index].isDone = false;
  42599. }
  42600. }
  42601. if (!returnValue) {
  42602. this._stopped = true;
  42603. }
  42604. return returnValue;
  42605. };
  42606. return RuntimeAnimation;
  42607. }());
  42608. BABYLON.RuntimeAnimation = RuntimeAnimation;
  42609. })(BABYLON || (BABYLON = {}));
  42610. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  42611. var BABYLON;
  42612. (function (BABYLON) {
  42613. var Animatable = /** @class */ (function () {
  42614. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  42615. if (fromFrame === void 0) { fromFrame = 0; }
  42616. if (toFrame === void 0) { toFrame = 100; }
  42617. if (loopAnimation === void 0) { loopAnimation = false; }
  42618. if (speedRatio === void 0) { speedRatio = 1.0; }
  42619. this.target = target;
  42620. this.fromFrame = fromFrame;
  42621. this.toFrame = toFrame;
  42622. this.loopAnimation = loopAnimation;
  42623. this.onAnimationEnd = onAnimationEnd;
  42624. this._localDelayOffset = null;
  42625. this._pausedDelay = null;
  42626. this._runtimeAnimations = new Array();
  42627. this._paused = false;
  42628. this._speedRatio = 1;
  42629. this.animationStarted = false;
  42630. if (animations) {
  42631. this.appendAnimations(target, animations);
  42632. }
  42633. this._speedRatio = speedRatio;
  42634. this._scene = scene;
  42635. scene._activeAnimatables.push(this);
  42636. }
  42637. Object.defineProperty(Animatable.prototype, "speedRatio", {
  42638. get: function () {
  42639. return this._speedRatio;
  42640. },
  42641. set: function (value) {
  42642. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  42643. var animation = this._runtimeAnimations[index];
  42644. animation._prepareForSpeedRatioChange(value);
  42645. }
  42646. this._speedRatio = value;
  42647. },
  42648. enumerable: true,
  42649. configurable: true
  42650. });
  42651. // Methods
  42652. Animatable.prototype.getAnimations = function () {
  42653. return this._runtimeAnimations;
  42654. };
  42655. Animatable.prototype.appendAnimations = function (target, animations) {
  42656. for (var index = 0; index < animations.length; index++) {
  42657. var animation = animations[index];
  42658. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  42659. }
  42660. };
  42661. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  42662. var runtimeAnimations = this._runtimeAnimations;
  42663. for (var index = 0; index < runtimeAnimations.length; index++) {
  42664. if (runtimeAnimations[index].animation.targetProperty === property) {
  42665. return runtimeAnimations[index].animation;
  42666. }
  42667. }
  42668. return null;
  42669. };
  42670. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  42671. var runtimeAnimations = this._runtimeAnimations;
  42672. for (var index = 0; index < runtimeAnimations.length; index++) {
  42673. if (runtimeAnimations[index].animation.targetProperty === property) {
  42674. return runtimeAnimations[index];
  42675. }
  42676. }
  42677. return null;
  42678. };
  42679. Animatable.prototype.reset = function () {
  42680. var runtimeAnimations = this._runtimeAnimations;
  42681. for (var index = 0; index < runtimeAnimations.length; index++) {
  42682. runtimeAnimations[index].reset();
  42683. }
  42684. // Reset to original value
  42685. for (index = 0; index < runtimeAnimations.length; index++) {
  42686. var animation = runtimeAnimations[index];
  42687. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  42688. }
  42689. this._localDelayOffset = null;
  42690. this._pausedDelay = null;
  42691. };
  42692. Animatable.prototype.enableBlending = function (blendingSpeed) {
  42693. var runtimeAnimations = this._runtimeAnimations;
  42694. for (var index = 0; index < runtimeAnimations.length; index++) {
  42695. runtimeAnimations[index].animation.enableBlending = true;
  42696. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  42697. }
  42698. };
  42699. Animatable.prototype.disableBlending = function () {
  42700. var runtimeAnimations = this._runtimeAnimations;
  42701. for (var index = 0; index < runtimeAnimations.length; index++) {
  42702. runtimeAnimations[index].animation.enableBlending = false;
  42703. }
  42704. };
  42705. Animatable.prototype.goToFrame = function (frame) {
  42706. var runtimeAnimations = this._runtimeAnimations;
  42707. if (runtimeAnimations[0]) {
  42708. var fps = runtimeAnimations[0].animation.framePerSecond;
  42709. var currentFrame = runtimeAnimations[0].currentFrame;
  42710. var adjustTime = frame - currentFrame;
  42711. var delay = adjustTime * 1000 / fps;
  42712. if (this._localDelayOffset === null) {
  42713. this._localDelayOffset = 0;
  42714. }
  42715. this._localDelayOffset -= delay;
  42716. }
  42717. for (var index = 0; index < runtimeAnimations.length; index++) {
  42718. runtimeAnimations[index].goToFrame(frame);
  42719. }
  42720. };
  42721. Animatable.prototype.pause = function () {
  42722. if (this._paused) {
  42723. return;
  42724. }
  42725. this._paused = true;
  42726. };
  42727. Animatable.prototype.restart = function () {
  42728. this._paused = false;
  42729. };
  42730. Animatable.prototype.stop = function (animationName) {
  42731. if (animationName) {
  42732. var idx = this._scene._activeAnimatables.indexOf(this);
  42733. if (idx > -1) {
  42734. var runtimeAnimations = this._runtimeAnimations;
  42735. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  42736. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  42737. continue;
  42738. }
  42739. runtimeAnimations[index].dispose();
  42740. runtimeAnimations.splice(index, 1);
  42741. }
  42742. if (runtimeAnimations.length == 0) {
  42743. this._scene._activeAnimatables.splice(idx, 1);
  42744. if (this.onAnimationEnd) {
  42745. this.onAnimationEnd();
  42746. }
  42747. }
  42748. }
  42749. }
  42750. else {
  42751. var index = this._scene._activeAnimatables.indexOf(this);
  42752. if (index > -1) {
  42753. this._scene._activeAnimatables.splice(index, 1);
  42754. var runtimeAnimations = this._runtimeAnimations;
  42755. for (var index = 0; index < runtimeAnimations.length; index++) {
  42756. runtimeAnimations[index].dispose();
  42757. }
  42758. if (this.onAnimationEnd) {
  42759. this.onAnimationEnd();
  42760. }
  42761. }
  42762. }
  42763. };
  42764. Animatable.prototype._animate = function (delay) {
  42765. if (this._paused) {
  42766. this.animationStarted = false;
  42767. if (this._pausedDelay === null) {
  42768. this._pausedDelay = delay;
  42769. }
  42770. return true;
  42771. }
  42772. if (this._localDelayOffset === null) {
  42773. this._localDelayOffset = delay;
  42774. }
  42775. else if (this._pausedDelay !== null) {
  42776. this._localDelayOffset += delay - this._pausedDelay;
  42777. this._pausedDelay = null;
  42778. }
  42779. // Animating
  42780. var running = false;
  42781. var runtimeAnimations = this._runtimeAnimations;
  42782. var index;
  42783. for (index = 0; index < runtimeAnimations.length; index++) {
  42784. var animation = runtimeAnimations[index];
  42785. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  42786. running = running || isRunning;
  42787. }
  42788. this.animationStarted = running;
  42789. if (!running) {
  42790. // Remove from active animatables
  42791. index = this._scene._activeAnimatables.indexOf(this);
  42792. this._scene._activeAnimatables.splice(index, 1);
  42793. // Dispose all runtime animations
  42794. for (index = 0; index < runtimeAnimations.length; index++) {
  42795. runtimeAnimations[index].dispose();
  42796. }
  42797. }
  42798. if (!running && this.onAnimationEnd) {
  42799. this.onAnimationEnd();
  42800. this.onAnimationEnd = null;
  42801. }
  42802. return running;
  42803. };
  42804. return Animatable;
  42805. }());
  42806. BABYLON.Animatable = Animatable;
  42807. })(BABYLON || (BABYLON = {}));
  42808. //# sourceMappingURL=babylon.animatable.js.map
  42809. var BABYLON;
  42810. (function (BABYLON) {
  42811. var EasingFunction = /** @class */ (function () {
  42812. function EasingFunction() {
  42813. // Properties
  42814. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  42815. }
  42816. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  42817. get: function () {
  42818. return EasingFunction._EASINGMODE_EASEIN;
  42819. },
  42820. enumerable: true,
  42821. configurable: true
  42822. });
  42823. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  42824. get: function () {
  42825. return EasingFunction._EASINGMODE_EASEOUT;
  42826. },
  42827. enumerable: true,
  42828. configurable: true
  42829. });
  42830. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  42831. get: function () {
  42832. return EasingFunction._EASINGMODE_EASEINOUT;
  42833. },
  42834. enumerable: true,
  42835. configurable: true
  42836. });
  42837. EasingFunction.prototype.setEasingMode = function (easingMode) {
  42838. var n = Math.min(Math.max(easingMode, 0), 2);
  42839. this._easingMode = n;
  42840. };
  42841. EasingFunction.prototype.getEasingMode = function () {
  42842. return this._easingMode;
  42843. };
  42844. EasingFunction.prototype.easeInCore = function (gradient) {
  42845. throw new Error('You must implement this method');
  42846. };
  42847. EasingFunction.prototype.ease = function (gradient) {
  42848. switch (this._easingMode) {
  42849. case EasingFunction.EASINGMODE_EASEIN:
  42850. return this.easeInCore(gradient);
  42851. case EasingFunction.EASINGMODE_EASEOUT:
  42852. return (1 - this.easeInCore(1 - gradient));
  42853. }
  42854. if (gradient >= 0.5) {
  42855. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  42856. }
  42857. return (this.easeInCore(gradient * 2) * 0.5);
  42858. };
  42859. //Statics
  42860. EasingFunction._EASINGMODE_EASEIN = 0;
  42861. EasingFunction._EASINGMODE_EASEOUT = 1;
  42862. EasingFunction._EASINGMODE_EASEINOUT = 2;
  42863. return EasingFunction;
  42864. }());
  42865. BABYLON.EasingFunction = EasingFunction;
  42866. var CircleEase = /** @class */ (function (_super) {
  42867. __extends(CircleEase, _super);
  42868. function CircleEase() {
  42869. return _super !== null && _super.apply(this, arguments) || this;
  42870. }
  42871. CircleEase.prototype.easeInCore = function (gradient) {
  42872. gradient = Math.max(0, Math.min(1, gradient));
  42873. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  42874. };
  42875. return CircleEase;
  42876. }(EasingFunction));
  42877. BABYLON.CircleEase = CircleEase;
  42878. var BackEase = /** @class */ (function (_super) {
  42879. __extends(BackEase, _super);
  42880. function BackEase(amplitude) {
  42881. if (amplitude === void 0) { amplitude = 1; }
  42882. var _this = _super.call(this) || this;
  42883. _this.amplitude = amplitude;
  42884. return _this;
  42885. }
  42886. BackEase.prototype.easeInCore = function (gradient) {
  42887. var num = Math.max(0, this.amplitude);
  42888. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  42889. };
  42890. return BackEase;
  42891. }(EasingFunction));
  42892. BABYLON.BackEase = BackEase;
  42893. var BounceEase = /** @class */ (function (_super) {
  42894. __extends(BounceEase, _super);
  42895. function BounceEase(bounces, bounciness) {
  42896. if (bounces === void 0) { bounces = 3; }
  42897. if (bounciness === void 0) { bounciness = 2; }
  42898. var _this = _super.call(this) || this;
  42899. _this.bounces = bounces;
  42900. _this.bounciness = bounciness;
  42901. return _this;
  42902. }
  42903. BounceEase.prototype.easeInCore = function (gradient) {
  42904. var y = Math.max(0.0, this.bounces);
  42905. var bounciness = this.bounciness;
  42906. if (bounciness <= 1.0) {
  42907. bounciness = 1.001;
  42908. }
  42909. var num9 = Math.pow(bounciness, y);
  42910. var num5 = 1.0 - bounciness;
  42911. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  42912. var num15 = gradient * num4;
  42913. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  42914. var num3 = Math.floor(num65);
  42915. var num13 = num3 + 1.0;
  42916. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  42917. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  42918. var num7 = (num8 + num12) * 0.5;
  42919. var num6 = gradient - num7;
  42920. var num2 = num7 - num8;
  42921. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  42922. };
  42923. return BounceEase;
  42924. }(EasingFunction));
  42925. BABYLON.BounceEase = BounceEase;
  42926. var CubicEase = /** @class */ (function (_super) {
  42927. __extends(CubicEase, _super);
  42928. function CubicEase() {
  42929. return _super !== null && _super.apply(this, arguments) || this;
  42930. }
  42931. CubicEase.prototype.easeInCore = function (gradient) {
  42932. return (gradient * gradient * gradient);
  42933. };
  42934. return CubicEase;
  42935. }(EasingFunction));
  42936. BABYLON.CubicEase = CubicEase;
  42937. var ElasticEase = /** @class */ (function (_super) {
  42938. __extends(ElasticEase, _super);
  42939. function ElasticEase(oscillations, springiness) {
  42940. if (oscillations === void 0) { oscillations = 3; }
  42941. if (springiness === void 0) { springiness = 3; }
  42942. var _this = _super.call(this) || this;
  42943. _this.oscillations = oscillations;
  42944. _this.springiness = springiness;
  42945. return _this;
  42946. }
  42947. ElasticEase.prototype.easeInCore = function (gradient) {
  42948. var num2;
  42949. var num3 = Math.max(0.0, this.oscillations);
  42950. var num = Math.max(0.0, this.springiness);
  42951. if (num == 0) {
  42952. num2 = gradient;
  42953. }
  42954. else {
  42955. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  42956. }
  42957. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  42958. };
  42959. return ElasticEase;
  42960. }(EasingFunction));
  42961. BABYLON.ElasticEase = ElasticEase;
  42962. var ExponentialEase = /** @class */ (function (_super) {
  42963. __extends(ExponentialEase, _super);
  42964. function ExponentialEase(exponent) {
  42965. if (exponent === void 0) { exponent = 2; }
  42966. var _this = _super.call(this) || this;
  42967. _this.exponent = exponent;
  42968. return _this;
  42969. }
  42970. ExponentialEase.prototype.easeInCore = function (gradient) {
  42971. if (this.exponent <= 0) {
  42972. return gradient;
  42973. }
  42974. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  42975. };
  42976. return ExponentialEase;
  42977. }(EasingFunction));
  42978. BABYLON.ExponentialEase = ExponentialEase;
  42979. var PowerEase = /** @class */ (function (_super) {
  42980. __extends(PowerEase, _super);
  42981. function PowerEase(power) {
  42982. if (power === void 0) { power = 2; }
  42983. var _this = _super.call(this) || this;
  42984. _this.power = power;
  42985. return _this;
  42986. }
  42987. PowerEase.prototype.easeInCore = function (gradient) {
  42988. var y = Math.max(0.0, this.power);
  42989. return Math.pow(gradient, y);
  42990. };
  42991. return PowerEase;
  42992. }(EasingFunction));
  42993. BABYLON.PowerEase = PowerEase;
  42994. var QuadraticEase = /** @class */ (function (_super) {
  42995. __extends(QuadraticEase, _super);
  42996. function QuadraticEase() {
  42997. return _super !== null && _super.apply(this, arguments) || this;
  42998. }
  42999. QuadraticEase.prototype.easeInCore = function (gradient) {
  43000. return (gradient * gradient);
  43001. };
  43002. return QuadraticEase;
  43003. }(EasingFunction));
  43004. BABYLON.QuadraticEase = QuadraticEase;
  43005. var QuarticEase = /** @class */ (function (_super) {
  43006. __extends(QuarticEase, _super);
  43007. function QuarticEase() {
  43008. return _super !== null && _super.apply(this, arguments) || this;
  43009. }
  43010. QuarticEase.prototype.easeInCore = function (gradient) {
  43011. return (gradient * gradient * gradient * gradient);
  43012. };
  43013. return QuarticEase;
  43014. }(EasingFunction));
  43015. BABYLON.QuarticEase = QuarticEase;
  43016. var QuinticEase = /** @class */ (function (_super) {
  43017. __extends(QuinticEase, _super);
  43018. function QuinticEase() {
  43019. return _super !== null && _super.apply(this, arguments) || this;
  43020. }
  43021. QuinticEase.prototype.easeInCore = function (gradient) {
  43022. return (gradient * gradient * gradient * gradient * gradient);
  43023. };
  43024. return QuinticEase;
  43025. }(EasingFunction));
  43026. BABYLON.QuinticEase = QuinticEase;
  43027. var SineEase = /** @class */ (function (_super) {
  43028. __extends(SineEase, _super);
  43029. function SineEase() {
  43030. return _super !== null && _super.apply(this, arguments) || this;
  43031. }
  43032. SineEase.prototype.easeInCore = function (gradient) {
  43033. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  43034. };
  43035. return SineEase;
  43036. }(EasingFunction));
  43037. BABYLON.SineEase = SineEase;
  43038. var BezierCurveEase = /** @class */ (function (_super) {
  43039. __extends(BezierCurveEase, _super);
  43040. function BezierCurveEase(x1, y1, x2, y2) {
  43041. if (x1 === void 0) { x1 = 0; }
  43042. if (y1 === void 0) { y1 = 0; }
  43043. if (x2 === void 0) { x2 = 1; }
  43044. if (y2 === void 0) { y2 = 1; }
  43045. var _this = _super.call(this) || this;
  43046. _this.x1 = x1;
  43047. _this.y1 = y1;
  43048. _this.x2 = x2;
  43049. _this.y2 = y2;
  43050. return _this;
  43051. }
  43052. BezierCurveEase.prototype.easeInCore = function (gradient) {
  43053. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  43054. };
  43055. return BezierCurveEase;
  43056. }(EasingFunction));
  43057. BABYLON.BezierCurveEase = BezierCurveEase;
  43058. })(BABYLON || (BABYLON = {}));
  43059. //# sourceMappingURL=babylon.easing.js.map
  43060. var BABYLON;
  43061. (function (BABYLON) {
  43062. var Condition = /** @class */ (function () {
  43063. function Condition(actionManager) {
  43064. this._actionManager = actionManager;
  43065. }
  43066. Condition.prototype.isValid = function () {
  43067. return true;
  43068. };
  43069. Condition.prototype._getProperty = function (propertyPath) {
  43070. return this._actionManager._getProperty(propertyPath);
  43071. };
  43072. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  43073. return this._actionManager._getEffectiveTarget(target, propertyPath);
  43074. };
  43075. Condition.prototype.serialize = function () {
  43076. };
  43077. Condition.prototype._serialize = function (serializedCondition) {
  43078. return {
  43079. type: 2,
  43080. children: [],
  43081. name: serializedCondition.name,
  43082. properties: serializedCondition.properties
  43083. };
  43084. };
  43085. return Condition;
  43086. }());
  43087. BABYLON.Condition = Condition;
  43088. var ValueCondition = /** @class */ (function (_super) {
  43089. __extends(ValueCondition, _super);
  43090. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  43091. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  43092. var _this = _super.call(this, actionManager) || this;
  43093. _this.propertyPath = propertyPath;
  43094. _this.value = value;
  43095. _this.operator = operator;
  43096. _this._target = target;
  43097. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  43098. _this._property = _this._getProperty(_this.propertyPath);
  43099. return _this;
  43100. }
  43101. Object.defineProperty(ValueCondition, "IsEqual", {
  43102. get: function () {
  43103. return ValueCondition._IsEqual;
  43104. },
  43105. enumerable: true,
  43106. configurable: true
  43107. });
  43108. Object.defineProperty(ValueCondition, "IsDifferent", {
  43109. get: function () {
  43110. return ValueCondition._IsDifferent;
  43111. },
  43112. enumerable: true,
  43113. configurable: true
  43114. });
  43115. Object.defineProperty(ValueCondition, "IsGreater", {
  43116. get: function () {
  43117. return ValueCondition._IsGreater;
  43118. },
  43119. enumerable: true,
  43120. configurable: true
  43121. });
  43122. Object.defineProperty(ValueCondition, "IsLesser", {
  43123. get: function () {
  43124. return ValueCondition._IsLesser;
  43125. },
  43126. enumerable: true,
  43127. configurable: true
  43128. });
  43129. // Methods
  43130. ValueCondition.prototype.isValid = function () {
  43131. switch (this.operator) {
  43132. case ValueCondition.IsGreater:
  43133. return this._effectiveTarget[this._property] > this.value;
  43134. case ValueCondition.IsLesser:
  43135. return this._effectiveTarget[this._property] < this.value;
  43136. case ValueCondition.IsEqual:
  43137. case ValueCondition.IsDifferent:
  43138. var check;
  43139. if (this.value.equals) {
  43140. check = this.value.equals(this._effectiveTarget[this._property]);
  43141. }
  43142. else {
  43143. check = this.value === this._effectiveTarget[this._property];
  43144. }
  43145. return this.operator === ValueCondition.IsEqual ? check : !check;
  43146. }
  43147. return false;
  43148. };
  43149. ValueCondition.prototype.serialize = function () {
  43150. return this._serialize({
  43151. name: "ValueCondition",
  43152. properties: [
  43153. BABYLON.Action._GetTargetProperty(this._target),
  43154. { name: "propertyPath", value: this.propertyPath },
  43155. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  43156. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  43157. ]
  43158. });
  43159. };
  43160. ValueCondition.GetOperatorName = function (operator) {
  43161. switch (operator) {
  43162. case ValueCondition._IsEqual: return "IsEqual";
  43163. case ValueCondition._IsDifferent: return "IsDifferent";
  43164. case ValueCondition._IsGreater: return "IsGreater";
  43165. case ValueCondition._IsLesser: return "IsLesser";
  43166. default: return "";
  43167. }
  43168. };
  43169. // Statics
  43170. ValueCondition._IsEqual = 0;
  43171. ValueCondition._IsDifferent = 1;
  43172. ValueCondition._IsGreater = 2;
  43173. ValueCondition._IsLesser = 3;
  43174. return ValueCondition;
  43175. }(Condition));
  43176. BABYLON.ValueCondition = ValueCondition;
  43177. var PredicateCondition = /** @class */ (function (_super) {
  43178. __extends(PredicateCondition, _super);
  43179. function PredicateCondition(actionManager, predicate) {
  43180. var _this = _super.call(this, actionManager) || this;
  43181. _this.predicate = predicate;
  43182. return _this;
  43183. }
  43184. PredicateCondition.prototype.isValid = function () {
  43185. return this.predicate();
  43186. };
  43187. return PredicateCondition;
  43188. }(Condition));
  43189. BABYLON.PredicateCondition = PredicateCondition;
  43190. var StateCondition = /** @class */ (function (_super) {
  43191. __extends(StateCondition, _super);
  43192. function StateCondition(actionManager, target, value) {
  43193. var _this = _super.call(this, actionManager) || this;
  43194. _this.value = value;
  43195. _this._target = target;
  43196. return _this;
  43197. }
  43198. // Methods
  43199. StateCondition.prototype.isValid = function () {
  43200. return this._target.state === this.value;
  43201. };
  43202. StateCondition.prototype.serialize = function () {
  43203. return this._serialize({
  43204. name: "StateCondition",
  43205. properties: [
  43206. BABYLON.Action._GetTargetProperty(this._target),
  43207. { name: "value", value: this.value }
  43208. ]
  43209. });
  43210. };
  43211. return StateCondition;
  43212. }(Condition));
  43213. BABYLON.StateCondition = StateCondition;
  43214. })(BABYLON || (BABYLON = {}));
  43215. //# sourceMappingURL=babylon.condition.js.map
  43216. var BABYLON;
  43217. (function (BABYLON) {
  43218. var Action = /** @class */ (function () {
  43219. function Action(triggerOptions, condition) {
  43220. this.triggerOptions = triggerOptions;
  43221. this.onBeforeExecuteObservable = new BABYLON.Observable();
  43222. if (triggerOptions.parameter) {
  43223. this.trigger = triggerOptions.trigger;
  43224. this._triggerParameter = triggerOptions.parameter;
  43225. }
  43226. else {
  43227. this.trigger = triggerOptions;
  43228. }
  43229. this._nextActiveAction = this;
  43230. this._condition = condition;
  43231. }
  43232. // Methods
  43233. Action.prototype._prepare = function () {
  43234. };
  43235. Action.prototype.getTriggerParameter = function () {
  43236. return this._triggerParameter;
  43237. };
  43238. Action.prototype._executeCurrent = function (evt) {
  43239. if (this._nextActiveAction._condition) {
  43240. var condition = this._nextActiveAction._condition;
  43241. var currentRenderId = this._actionManager.getScene().getRenderId();
  43242. // We cache the current evaluation for the current frame
  43243. if (condition._evaluationId === currentRenderId) {
  43244. if (!condition._currentResult) {
  43245. return;
  43246. }
  43247. }
  43248. else {
  43249. condition._evaluationId = currentRenderId;
  43250. if (!condition.isValid()) {
  43251. condition._currentResult = false;
  43252. return;
  43253. }
  43254. condition._currentResult = true;
  43255. }
  43256. }
  43257. this.onBeforeExecuteObservable.notifyObservers(this);
  43258. this._nextActiveAction.execute(evt);
  43259. this.skipToNextActiveAction();
  43260. };
  43261. Action.prototype.execute = function (evt) {
  43262. };
  43263. Action.prototype.skipToNextActiveAction = function () {
  43264. if (this._nextActiveAction._child) {
  43265. if (!this._nextActiveAction._child._actionManager) {
  43266. this._nextActiveAction._child._actionManager = this._actionManager;
  43267. }
  43268. this._nextActiveAction = this._nextActiveAction._child;
  43269. }
  43270. else {
  43271. this._nextActiveAction = this;
  43272. }
  43273. };
  43274. Action.prototype.then = function (action) {
  43275. this._child = action;
  43276. action._actionManager = this._actionManager;
  43277. action._prepare();
  43278. return action;
  43279. };
  43280. Action.prototype._getProperty = function (propertyPath) {
  43281. return this._actionManager._getProperty(propertyPath);
  43282. };
  43283. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  43284. return this._actionManager._getEffectiveTarget(target, propertyPath);
  43285. };
  43286. Action.prototype.serialize = function (parent) {
  43287. };
  43288. // Called by BABYLON.Action objects in serialize(...). Internal use
  43289. Action.prototype._serialize = function (serializedAction, parent) {
  43290. var serializationObject = {
  43291. type: 1,
  43292. children: [],
  43293. name: serializedAction.name,
  43294. properties: serializedAction.properties || []
  43295. };
  43296. // Serialize child
  43297. if (this._child) {
  43298. this._child.serialize(serializationObject);
  43299. }
  43300. // Check if "this" has a condition
  43301. if (this._condition) {
  43302. var serializedCondition = this._condition.serialize();
  43303. serializedCondition.children.push(serializationObject);
  43304. if (parent) {
  43305. parent.children.push(serializedCondition);
  43306. }
  43307. return serializedCondition;
  43308. }
  43309. if (parent) {
  43310. parent.children.push(serializationObject);
  43311. }
  43312. return serializationObject;
  43313. };
  43314. Action._SerializeValueAsString = function (value) {
  43315. if (typeof value === "number") {
  43316. return value.toString();
  43317. }
  43318. if (typeof value === "boolean") {
  43319. return value ? "true" : "false";
  43320. }
  43321. if (value instanceof BABYLON.Vector2) {
  43322. return value.x + ", " + value.y;
  43323. }
  43324. if (value instanceof BABYLON.Vector3) {
  43325. return value.x + ", " + value.y + ", " + value.z;
  43326. }
  43327. if (value instanceof BABYLON.Color3) {
  43328. return value.r + ", " + value.g + ", " + value.b;
  43329. }
  43330. if (value instanceof BABYLON.Color4) {
  43331. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  43332. }
  43333. return value; // string
  43334. };
  43335. Action._GetTargetProperty = function (target) {
  43336. return {
  43337. name: "target",
  43338. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  43339. : target instanceof BABYLON.Light ? "LightProperties"
  43340. : target instanceof BABYLON.Camera ? "CameraProperties"
  43341. : "SceneProperties",
  43342. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  43343. };
  43344. };
  43345. return Action;
  43346. }());
  43347. BABYLON.Action = Action;
  43348. })(BABYLON || (BABYLON = {}));
  43349. //# sourceMappingURL=babylon.action.js.map
  43350. var BABYLON;
  43351. (function (BABYLON) {
  43352. /**
  43353. * ActionEvent is the event beint sent when an action is triggered.
  43354. */
  43355. var ActionEvent = /** @class */ (function () {
  43356. /**
  43357. * @param source The mesh or sprite that triggered the action.
  43358. * @param pointerX The X mouse cursor position at the time of the event
  43359. * @param pointerY The Y mouse cursor position at the time of the event
  43360. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  43361. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  43362. */
  43363. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  43364. this.source = source;
  43365. this.pointerX = pointerX;
  43366. this.pointerY = pointerY;
  43367. this.meshUnderPointer = meshUnderPointer;
  43368. this.sourceEvent = sourceEvent;
  43369. this.additionalData = additionalData;
  43370. }
  43371. /**
  43372. * Helper function to auto-create an ActionEvent from a source mesh.
  43373. * @param source The source mesh that triggered the event
  43374. * @param evt {Event} The original (browser) event
  43375. */
  43376. ActionEvent.CreateNew = function (source, evt, additionalData) {
  43377. var scene = source.getScene();
  43378. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  43379. };
  43380. /**
  43381. * Helper function to auto-create an ActionEvent from a source mesh.
  43382. * @param source The source sprite that triggered the event
  43383. * @param scene Scene associated with the sprite
  43384. * @param evt {Event} The original (browser) event
  43385. */
  43386. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  43387. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  43388. };
  43389. /**
  43390. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  43391. * @param scene the scene where the event occurred
  43392. * @param evt {Event} The original (browser) event
  43393. */
  43394. ActionEvent.CreateNewFromScene = function (scene, evt) {
  43395. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  43396. };
  43397. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  43398. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  43399. };
  43400. return ActionEvent;
  43401. }());
  43402. BABYLON.ActionEvent = ActionEvent;
  43403. /**
  43404. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  43405. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  43406. */
  43407. var ActionManager = /** @class */ (function () {
  43408. function ActionManager(scene) {
  43409. // Members
  43410. this.actions = new Array();
  43411. this.hoverCursor = '';
  43412. this._scene = scene;
  43413. scene._actionManagers.push(this);
  43414. }
  43415. Object.defineProperty(ActionManager, "NothingTrigger", {
  43416. get: function () {
  43417. return ActionManager._NothingTrigger;
  43418. },
  43419. enumerable: true,
  43420. configurable: true
  43421. });
  43422. Object.defineProperty(ActionManager, "OnPickTrigger", {
  43423. get: function () {
  43424. return ActionManager._OnPickTrigger;
  43425. },
  43426. enumerable: true,
  43427. configurable: true
  43428. });
  43429. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  43430. get: function () {
  43431. return ActionManager._OnLeftPickTrigger;
  43432. },
  43433. enumerable: true,
  43434. configurable: true
  43435. });
  43436. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  43437. get: function () {
  43438. return ActionManager._OnRightPickTrigger;
  43439. },
  43440. enumerable: true,
  43441. configurable: true
  43442. });
  43443. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  43444. get: function () {
  43445. return ActionManager._OnCenterPickTrigger;
  43446. },
  43447. enumerable: true,
  43448. configurable: true
  43449. });
  43450. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  43451. get: function () {
  43452. return ActionManager._OnPickDownTrigger;
  43453. },
  43454. enumerable: true,
  43455. configurable: true
  43456. });
  43457. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  43458. get: function () {
  43459. return ActionManager._OnDoublePickTrigger;
  43460. },
  43461. enumerable: true,
  43462. configurable: true
  43463. });
  43464. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  43465. get: function () {
  43466. return ActionManager._OnPickUpTrigger;
  43467. },
  43468. enumerable: true,
  43469. configurable: true
  43470. });
  43471. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  43472. /// This trigger will only be raised if you also declared a OnPickDown
  43473. get: function () {
  43474. return ActionManager._OnPickOutTrigger;
  43475. },
  43476. enumerable: true,
  43477. configurable: true
  43478. });
  43479. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  43480. get: function () {
  43481. return ActionManager._OnLongPressTrigger;
  43482. },
  43483. enumerable: true,
  43484. configurable: true
  43485. });
  43486. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  43487. get: function () {
  43488. return ActionManager._OnPointerOverTrigger;
  43489. },
  43490. enumerable: true,
  43491. configurable: true
  43492. });
  43493. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  43494. get: function () {
  43495. return ActionManager._OnPointerOutTrigger;
  43496. },
  43497. enumerable: true,
  43498. configurable: true
  43499. });
  43500. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  43501. get: function () {
  43502. return ActionManager._OnEveryFrameTrigger;
  43503. },
  43504. enumerable: true,
  43505. configurable: true
  43506. });
  43507. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  43508. get: function () {
  43509. return ActionManager._OnIntersectionEnterTrigger;
  43510. },
  43511. enumerable: true,
  43512. configurable: true
  43513. });
  43514. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  43515. get: function () {
  43516. return ActionManager._OnIntersectionExitTrigger;
  43517. },
  43518. enumerable: true,
  43519. configurable: true
  43520. });
  43521. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  43522. get: function () {
  43523. return ActionManager._OnKeyDownTrigger;
  43524. },
  43525. enumerable: true,
  43526. configurable: true
  43527. });
  43528. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  43529. get: function () {
  43530. return ActionManager._OnKeyUpTrigger;
  43531. },
  43532. enumerable: true,
  43533. configurable: true
  43534. });
  43535. // Methods
  43536. ActionManager.prototype.dispose = function () {
  43537. var index = this._scene._actionManagers.indexOf(this);
  43538. for (var i = 0; i < this.actions.length; i++) {
  43539. var action = this.actions[i];
  43540. ActionManager.Triggers[action.trigger]--;
  43541. if (ActionManager.Triggers[action.trigger] === 0) {
  43542. delete ActionManager.Triggers[action.trigger];
  43543. }
  43544. }
  43545. if (index > -1) {
  43546. this._scene._actionManagers.splice(index, 1);
  43547. }
  43548. };
  43549. ActionManager.prototype.getScene = function () {
  43550. return this._scene;
  43551. };
  43552. /**
  43553. * Does this action manager handles actions of any of the given triggers
  43554. * @param {number[]} triggers - the triggers to be tested
  43555. * @return {boolean} whether one (or more) of the triggers is handeled
  43556. */
  43557. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  43558. for (var index = 0; index < this.actions.length; index++) {
  43559. var action = this.actions[index];
  43560. if (triggers.indexOf(action.trigger) > -1) {
  43561. return true;
  43562. }
  43563. }
  43564. return false;
  43565. };
  43566. /**
  43567. * Does this action manager handles actions of a given trigger
  43568. * @param {number} trigger - the trigger to be tested
  43569. * @return {boolean} whether the trigger is handeled
  43570. */
  43571. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  43572. for (var index = 0; index < this.actions.length; index++) {
  43573. var action = this.actions[index];
  43574. if (action.trigger === trigger) {
  43575. return true;
  43576. }
  43577. }
  43578. return false;
  43579. };
  43580. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  43581. /**
  43582. * Does this action manager has pointer triggers
  43583. * @return {boolean} whether or not it has pointer triggers
  43584. */
  43585. get: function () {
  43586. for (var index = 0; index < this.actions.length; index++) {
  43587. var action = this.actions[index];
  43588. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  43589. return true;
  43590. }
  43591. }
  43592. return false;
  43593. },
  43594. enumerable: true,
  43595. configurable: true
  43596. });
  43597. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  43598. /**
  43599. * Does this action manager has pick triggers
  43600. * @return {boolean} whether or not it has pick triggers
  43601. */
  43602. get: function () {
  43603. for (var index = 0; index < this.actions.length; index++) {
  43604. var action = this.actions[index];
  43605. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  43606. return true;
  43607. }
  43608. }
  43609. return false;
  43610. },
  43611. enumerable: true,
  43612. configurable: true
  43613. });
  43614. Object.defineProperty(ActionManager, "HasTriggers", {
  43615. /**
  43616. * Does exist one action manager with at least one trigger
  43617. * @return {boolean} whether or not it exists one action manager with one trigger
  43618. **/
  43619. get: function () {
  43620. for (var t in ActionManager.Triggers) {
  43621. if (ActionManager.Triggers.hasOwnProperty(t)) {
  43622. return true;
  43623. }
  43624. }
  43625. return false;
  43626. },
  43627. enumerable: true,
  43628. configurable: true
  43629. });
  43630. Object.defineProperty(ActionManager, "HasPickTriggers", {
  43631. /**
  43632. * Does exist one action manager with at least one pick trigger
  43633. * @return {boolean} whether or not it exists one action manager with one pick trigger
  43634. **/
  43635. get: function () {
  43636. for (var t in ActionManager.Triggers) {
  43637. if (ActionManager.Triggers.hasOwnProperty(t)) {
  43638. var t_int = parseInt(t);
  43639. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  43640. return true;
  43641. }
  43642. }
  43643. }
  43644. return false;
  43645. },
  43646. enumerable: true,
  43647. configurable: true
  43648. });
  43649. /**
  43650. * Does exist one action manager that handles actions of a given trigger
  43651. * @param {number} trigger - the trigger to be tested
  43652. * @return {boolean} whether the trigger is handeled by at least one action manager
  43653. **/
  43654. ActionManager.HasSpecificTrigger = function (trigger) {
  43655. for (var t in ActionManager.Triggers) {
  43656. if (ActionManager.Triggers.hasOwnProperty(t)) {
  43657. var t_int = parseInt(t);
  43658. if (t_int === trigger) {
  43659. return true;
  43660. }
  43661. }
  43662. }
  43663. return false;
  43664. };
  43665. /**
  43666. * Registers an action to this action manager
  43667. * @param {BABYLON.Action} action - the action to be registered
  43668. * @return {BABYLON.Action} the action amended (prepared) after registration
  43669. */
  43670. ActionManager.prototype.registerAction = function (action) {
  43671. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  43672. if (this.getScene().actionManager !== this) {
  43673. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  43674. return null;
  43675. }
  43676. }
  43677. this.actions.push(action);
  43678. if (ActionManager.Triggers[action.trigger]) {
  43679. ActionManager.Triggers[action.trigger]++;
  43680. }
  43681. else {
  43682. ActionManager.Triggers[action.trigger] = 1;
  43683. }
  43684. action._actionManager = this;
  43685. action._prepare();
  43686. return action;
  43687. };
  43688. /**
  43689. * Process a specific trigger
  43690. * @param {number} trigger - the trigger to process
  43691. * @param evt {BABYLON.ActionEvent} the event details to be processed
  43692. */
  43693. ActionManager.prototype.processTrigger = function (trigger, evt) {
  43694. for (var index = 0; index < this.actions.length; index++) {
  43695. var action = this.actions[index];
  43696. if (action.trigger === trigger) {
  43697. if (evt) {
  43698. if (trigger === ActionManager.OnKeyUpTrigger
  43699. || trigger === ActionManager.OnKeyDownTrigger) {
  43700. var parameter = action.getTriggerParameter();
  43701. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  43702. if (!parameter.toLowerCase) {
  43703. continue;
  43704. }
  43705. var lowerCase = parameter.toLowerCase();
  43706. if (lowerCase !== evt.sourceEvent.key) {
  43707. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  43708. var actualkey = String.fromCharCode(unicode).toLowerCase();
  43709. if (actualkey !== lowerCase) {
  43710. continue;
  43711. }
  43712. }
  43713. }
  43714. }
  43715. }
  43716. action._executeCurrent(evt);
  43717. }
  43718. }
  43719. };
  43720. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  43721. var properties = propertyPath.split(".");
  43722. for (var index = 0; index < properties.length - 1; index++) {
  43723. target = target[properties[index]];
  43724. }
  43725. return target;
  43726. };
  43727. ActionManager.prototype._getProperty = function (propertyPath) {
  43728. var properties = propertyPath.split(".");
  43729. return properties[properties.length - 1];
  43730. };
  43731. ActionManager.prototype.serialize = function (name) {
  43732. var root = {
  43733. children: new Array(),
  43734. name: name,
  43735. type: 3,
  43736. properties: new Array() // Empty for root but required
  43737. };
  43738. for (var i = 0; i < this.actions.length; i++) {
  43739. var triggerObject = {
  43740. type: 0,
  43741. children: new Array(),
  43742. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  43743. properties: new Array()
  43744. };
  43745. var triggerOptions = this.actions[i].triggerOptions;
  43746. if (triggerOptions && typeof triggerOptions !== "number") {
  43747. if (triggerOptions.parameter instanceof BABYLON.Node) {
  43748. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  43749. }
  43750. else {
  43751. var parameter = {};
  43752. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  43753. if (triggerOptions.parameter.mesh) {
  43754. parameter._meshId = triggerOptions.parameter.mesh.id;
  43755. }
  43756. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  43757. }
  43758. }
  43759. // Serialize child action, recursively
  43760. this.actions[i].serialize(triggerObject);
  43761. // Add serialized trigger
  43762. root.children.push(triggerObject);
  43763. }
  43764. return root;
  43765. };
  43766. ActionManager.Parse = function (parsedActions, object, scene) {
  43767. var actionManager = new ActionManager(scene);
  43768. if (object === null)
  43769. scene.actionManager = actionManager;
  43770. else
  43771. object.actionManager = actionManager;
  43772. // instanciate a new object
  43773. var instanciate = function (name, params) {
  43774. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  43775. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  43776. newInstance.constructor.apply(newInstance, params);
  43777. return newInstance;
  43778. };
  43779. var parseParameter = function (name, value, target, propertyPath) {
  43780. if (propertyPath === null) {
  43781. // String, boolean or float
  43782. var floatValue = parseFloat(value);
  43783. if (value === "true" || value === "false")
  43784. return value === "true";
  43785. else
  43786. return isNaN(floatValue) ? value : floatValue;
  43787. }
  43788. var effectiveTarget = propertyPath.split(".");
  43789. var values = value.split(",");
  43790. // Get effective Target
  43791. for (var i = 0; i < effectiveTarget.length; i++) {
  43792. target = target[effectiveTarget[i]];
  43793. }
  43794. // Return appropriate value with its type
  43795. if (typeof (target) === "boolean")
  43796. return values[0] === "true";
  43797. if (typeof (target) === "string")
  43798. return values[0];
  43799. // Parameters with multiple values such as Vector3 etc.
  43800. var split = new Array();
  43801. for (var i = 0; i < values.length; i++)
  43802. split.push(parseFloat(values[i]));
  43803. if (target instanceof BABYLON.Vector3)
  43804. return BABYLON.Vector3.FromArray(split);
  43805. if (target instanceof BABYLON.Vector4)
  43806. return BABYLON.Vector4.FromArray(split);
  43807. if (target instanceof BABYLON.Color3)
  43808. return BABYLON.Color3.FromArray(split);
  43809. if (target instanceof BABYLON.Color4)
  43810. return BABYLON.Color4.FromArray(split);
  43811. return parseFloat(values[0]);
  43812. };
  43813. // traverse graph per trigger
  43814. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  43815. if (combineArray === void 0) { combineArray = null; }
  43816. if (parsedAction.detached)
  43817. return;
  43818. var parameters = new Array();
  43819. var target = null;
  43820. var propertyPath = null;
  43821. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  43822. // Parameters
  43823. if (parsedAction.type === 2)
  43824. parameters.push(actionManager);
  43825. else
  43826. parameters.push(trigger);
  43827. if (combine) {
  43828. var actions = new Array();
  43829. for (var j = 0; j < parsedAction.combine.length; j++) {
  43830. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  43831. }
  43832. parameters.push(actions);
  43833. }
  43834. else {
  43835. for (var i = 0; i < parsedAction.properties.length; i++) {
  43836. var value = parsedAction.properties[i].value;
  43837. var name = parsedAction.properties[i].name;
  43838. var targetType = parsedAction.properties[i].targetType;
  43839. if (name === "target")
  43840. if (targetType !== null && targetType === "SceneProperties")
  43841. value = target = scene;
  43842. else
  43843. value = target = scene.getNodeByName(value);
  43844. else if (name === "parent")
  43845. value = scene.getNodeByName(value);
  43846. else if (name === "sound")
  43847. value = scene.getSoundByName(value);
  43848. else if (name !== "propertyPath") {
  43849. if (parsedAction.type === 2 && name === "operator")
  43850. value = BABYLON.ValueCondition[value];
  43851. else
  43852. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  43853. }
  43854. else {
  43855. propertyPath = value;
  43856. }
  43857. parameters.push(value);
  43858. }
  43859. }
  43860. if (combineArray === null) {
  43861. parameters.push(condition);
  43862. }
  43863. else {
  43864. parameters.push(null);
  43865. }
  43866. // If interpolate value action
  43867. if (parsedAction.name === "InterpolateValueAction") {
  43868. var param = parameters[parameters.length - 2];
  43869. parameters[parameters.length - 1] = param;
  43870. parameters[parameters.length - 2] = condition;
  43871. }
  43872. // Action or condition(s) and not CombineAction
  43873. var newAction = instanciate(parsedAction.name, parameters);
  43874. if (newAction instanceof BABYLON.Condition && condition !== null) {
  43875. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  43876. if (action)
  43877. action.then(nothing);
  43878. else
  43879. actionManager.registerAction(nothing);
  43880. action = nothing;
  43881. }
  43882. if (combineArray === null) {
  43883. if (newAction instanceof BABYLON.Condition) {
  43884. condition = newAction;
  43885. newAction = action;
  43886. }
  43887. else {
  43888. condition = null;
  43889. if (action)
  43890. action.then(newAction);
  43891. else
  43892. actionManager.registerAction(newAction);
  43893. }
  43894. }
  43895. else {
  43896. combineArray.push(newAction);
  43897. }
  43898. for (var i = 0; i < parsedAction.children.length; i++)
  43899. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  43900. };
  43901. // triggers
  43902. for (var i = 0; i < parsedActions.children.length; i++) {
  43903. var triggerParams;
  43904. var trigger = parsedActions.children[i];
  43905. if (trigger.properties.length > 0) {
  43906. var param = trigger.properties[0].value;
  43907. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  43908. if (value._meshId) {
  43909. value.mesh = scene.getMeshByID(value._meshId);
  43910. }
  43911. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  43912. }
  43913. else
  43914. triggerParams = ActionManager[trigger.name];
  43915. for (var j = 0; j < trigger.children.length; j++) {
  43916. if (!trigger.detached)
  43917. traverse(trigger.children[j], triggerParams, null, null);
  43918. }
  43919. }
  43920. };
  43921. ActionManager.GetTriggerName = function (trigger) {
  43922. switch (trigger) {
  43923. case 0: return "NothingTrigger";
  43924. case 1: return "OnPickTrigger";
  43925. case 2: return "OnLeftPickTrigger";
  43926. case 3: return "OnRightPickTrigger";
  43927. case 4: return "OnCenterPickTrigger";
  43928. case 5: return "OnPickDownTrigger";
  43929. case 6: return "OnPickUpTrigger";
  43930. case 7: return "OnLongPressTrigger";
  43931. case 8: return "OnPointerOverTrigger";
  43932. case 9: return "OnPointerOutTrigger";
  43933. case 10: return "OnEveryFrameTrigger";
  43934. case 11: return "OnIntersectionEnterTrigger";
  43935. case 12: return "OnIntersectionExitTrigger";
  43936. case 13: return "OnKeyDownTrigger";
  43937. case 14: return "OnKeyUpTrigger";
  43938. case 15: return "OnPickOutTrigger";
  43939. default: return "";
  43940. }
  43941. };
  43942. // Statics
  43943. ActionManager._NothingTrigger = 0;
  43944. ActionManager._OnPickTrigger = 1;
  43945. ActionManager._OnLeftPickTrigger = 2;
  43946. ActionManager._OnRightPickTrigger = 3;
  43947. ActionManager._OnCenterPickTrigger = 4;
  43948. ActionManager._OnPickDownTrigger = 5;
  43949. ActionManager._OnDoublePickTrigger = 6;
  43950. ActionManager._OnPickUpTrigger = 7;
  43951. ActionManager._OnLongPressTrigger = 8;
  43952. ActionManager._OnPointerOverTrigger = 9;
  43953. ActionManager._OnPointerOutTrigger = 10;
  43954. ActionManager._OnEveryFrameTrigger = 11;
  43955. ActionManager._OnIntersectionEnterTrigger = 12;
  43956. ActionManager._OnIntersectionExitTrigger = 13;
  43957. ActionManager._OnKeyDownTrigger = 14;
  43958. ActionManager._OnKeyUpTrigger = 15;
  43959. ActionManager._OnPickOutTrigger = 16;
  43960. ActionManager.Triggers = {};
  43961. return ActionManager;
  43962. }());
  43963. BABYLON.ActionManager = ActionManager;
  43964. })(BABYLON || (BABYLON = {}));
  43965. //# sourceMappingURL=babylon.actionManager.js.map
  43966. var BABYLON;
  43967. (function (BABYLON) {
  43968. var InterpolateValueAction = /** @class */ (function (_super) {
  43969. __extends(InterpolateValueAction, _super);
  43970. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  43971. if (duration === void 0) { duration = 1000; }
  43972. var _this = _super.call(this, triggerOptions, condition) || this;
  43973. _this.propertyPath = propertyPath;
  43974. _this.value = value;
  43975. _this.duration = duration;
  43976. _this.stopOtherAnimations = stopOtherAnimations;
  43977. _this.onInterpolationDone = onInterpolationDone;
  43978. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  43979. _this._target = _this._effectiveTarget = target;
  43980. return _this;
  43981. }
  43982. InterpolateValueAction.prototype._prepare = function () {
  43983. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  43984. this._property = this._getProperty(this.propertyPath);
  43985. };
  43986. InterpolateValueAction.prototype.execute = function () {
  43987. var _this = this;
  43988. var scene = this._actionManager.getScene();
  43989. var keys = [
  43990. {
  43991. frame: 0,
  43992. value: this._effectiveTarget[this._property]
  43993. }, {
  43994. frame: 100,
  43995. value: this.value
  43996. }
  43997. ];
  43998. var dataType;
  43999. if (typeof this.value === "number") {
  44000. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  44001. }
  44002. else if (this.value instanceof BABYLON.Color3) {
  44003. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  44004. }
  44005. else if (this.value instanceof BABYLON.Vector3) {
  44006. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  44007. }
  44008. else if (this.value instanceof BABYLON.Matrix) {
  44009. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  44010. }
  44011. else if (this.value instanceof BABYLON.Quaternion) {
  44012. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  44013. }
  44014. else {
  44015. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  44016. return;
  44017. }
  44018. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  44019. animation.setKeys(keys);
  44020. if (this.stopOtherAnimations) {
  44021. scene.stopAnimation(this._effectiveTarget);
  44022. }
  44023. var wrapper = function () {
  44024. _this.onInterpolationDoneObservable.notifyObservers(_this);
  44025. if (_this.onInterpolationDone) {
  44026. _this.onInterpolationDone();
  44027. }
  44028. };
  44029. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  44030. };
  44031. InterpolateValueAction.prototype.serialize = function (parent) {
  44032. return _super.prototype._serialize.call(this, {
  44033. name: "InterpolateValueAction",
  44034. properties: [
  44035. BABYLON.Action._GetTargetProperty(this._target),
  44036. { name: "propertyPath", value: this.propertyPath },
  44037. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  44038. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  44039. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  44040. ]
  44041. }, parent);
  44042. };
  44043. return InterpolateValueAction;
  44044. }(BABYLON.Action));
  44045. BABYLON.InterpolateValueAction = InterpolateValueAction;
  44046. })(BABYLON || (BABYLON = {}));
  44047. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  44048. var BABYLON;
  44049. (function (BABYLON) {
  44050. var SwitchBooleanAction = /** @class */ (function (_super) {
  44051. __extends(SwitchBooleanAction, _super);
  44052. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  44053. var _this = _super.call(this, triggerOptions, condition) || this;
  44054. _this.propertyPath = propertyPath;
  44055. _this._target = _this._effectiveTarget = target;
  44056. return _this;
  44057. }
  44058. SwitchBooleanAction.prototype._prepare = function () {
  44059. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44060. this._property = this._getProperty(this.propertyPath);
  44061. };
  44062. SwitchBooleanAction.prototype.execute = function () {
  44063. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  44064. };
  44065. SwitchBooleanAction.prototype.serialize = function (parent) {
  44066. return _super.prototype._serialize.call(this, {
  44067. name: "SwitchBooleanAction",
  44068. properties: [
  44069. BABYLON.Action._GetTargetProperty(this._target),
  44070. { name: "propertyPath", value: this.propertyPath }
  44071. ]
  44072. }, parent);
  44073. };
  44074. return SwitchBooleanAction;
  44075. }(BABYLON.Action));
  44076. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  44077. var SetStateAction = /** @class */ (function (_super) {
  44078. __extends(SetStateAction, _super);
  44079. function SetStateAction(triggerOptions, target, value, condition) {
  44080. var _this = _super.call(this, triggerOptions, condition) || this;
  44081. _this.value = value;
  44082. _this._target = target;
  44083. return _this;
  44084. }
  44085. SetStateAction.prototype.execute = function () {
  44086. this._target.state = this.value;
  44087. };
  44088. SetStateAction.prototype.serialize = function (parent) {
  44089. return _super.prototype._serialize.call(this, {
  44090. name: "SetStateAction",
  44091. properties: [
  44092. BABYLON.Action._GetTargetProperty(this._target),
  44093. { name: "value", value: this.value }
  44094. ]
  44095. }, parent);
  44096. };
  44097. return SetStateAction;
  44098. }(BABYLON.Action));
  44099. BABYLON.SetStateAction = SetStateAction;
  44100. var SetValueAction = /** @class */ (function (_super) {
  44101. __extends(SetValueAction, _super);
  44102. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  44103. var _this = _super.call(this, triggerOptions, condition) || this;
  44104. _this.propertyPath = propertyPath;
  44105. _this.value = value;
  44106. _this._target = _this._effectiveTarget = target;
  44107. return _this;
  44108. }
  44109. SetValueAction.prototype._prepare = function () {
  44110. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44111. this._property = this._getProperty(this.propertyPath);
  44112. };
  44113. SetValueAction.prototype.execute = function () {
  44114. this._effectiveTarget[this._property] = this.value;
  44115. if (this._target.markAsDirty) {
  44116. this._target.markAsDirty(this._property);
  44117. }
  44118. };
  44119. SetValueAction.prototype.serialize = function (parent) {
  44120. return _super.prototype._serialize.call(this, {
  44121. name: "SetValueAction",
  44122. properties: [
  44123. BABYLON.Action._GetTargetProperty(this._target),
  44124. { name: "propertyPath", value: this.propertyPath },
  44125. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  44126. ]
  44127. }, parent);
  44128. };
  44129. return SetValueAction;
  44130. }(BABYLON.Action));
  44131. BABYLON.SetValueAction = SetValueAction;
  44132. var IncrementValueAction = /** @class */ (function (_super) {
  44133. __extends(IncrementValueAction, _super);
  44134. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  44135. var _this = _super.call(this, triggerOptions, condition) || this;
  44136. _this.propertyPath = propertyPath;
  44137. _this.value = value;
  44138. _this._target = _this._effectiveTarget = target;
  44139. return _this;
  44140. }
  44141. IncrementValueAction.prototype._prepare = function () {
  44142. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44143. this._property = this._getProperty(this.propertyPath);
  44144. if (typeof this._effectiveTarget[this._property] !== "number") {
  44145. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  44146. }
  44147. };
  44148. IncrementValueAction.prototype.execute = function () {
  44149. this._effectiveTarget[this._property] += this.value;
  44150. if (this._target.markAsDirty) {
  44151. this._target.markAsDirty(this._property);
  44152. }
  44153. };
  44154. IncrementValueAction.prototype.serialize = function (parent) {
  44155. return _super.prototype._serialize.call(this, {
  44156. name: "IncrementValueAction",
  44157. properties: [
  44158. BABYLON.Action._GetTargetProperty(this._target),
  44159. { name: "propertyPath", value: this.propertyPath },
  44160. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  44161. ]
  44162. }, parent);
  44163. };
  44164. return IncrementValueAction;
  44165. }(BABYLON.Action));
  44166. BABYLON.IncrementValueAction = IncrementValueAction;
  44167. var PlayAnimationAction = /** @class */ (function (_super) {
  44168. __extends(PlayAnimationAction, _super);
  44169. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  44170. var _this = _super.call(this, triggerOptions, condition) || this;
  44171. _this.from = from;
  44172. _this.to = to;
  44173. _this.loop = loop;
  44174. _this._target = target;
  44175. return _this;
  44176. }
  44177. PlayAnimationAction.prototype._prepare = function () {
  44178. };
  44179. PlayAnimationAction.prototype.execute = function () {
  44180. var scene = this._actionManager.getScene();
  44181. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  44182. };
  44183. PlayAnimationAction.prototype.serialize = function (parent) {
  44184. return _super.prototype._serialize.call(this, {
  44185. name: "PlayAnimationAction",
  44186. properties: [
  44187. BABYLON.Action._GetTargetProperty(this._target),
  44188. { name: "from", value: String(this.from) },
  44189. { name: "to", value: String(this.to) },
  44190. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  44191. ]
  44192. }, parent);
  44193. };
  44194. return PlayAnimationAction;
  44195. }(BABYLON.Action));
  44196. BABYLON.PlayAnimationAction = PlayAnimationAction;
  44197. var StopAnimationAction = /** @class */ (function (_super) {
  44198. __extends(StopAnimationAction, _super);
  44199. function StopAnimationAction(triggerOptions, target, condition) {
  44200. var _this = _super.call(this, triggerOptions, condition) || this;
  44201. _this._target = target;
  44202. return _this;
  44203. }
  44204. StopAnimationAction.prototype._prepare = function () {
  44205. };
  44206. StopAnimationAction.prototype.execute = function () {
  44207. var scene = this._actionManager.getScene();
  44208. scene.stopAnimation(this._target);
  44209. };
  44210. StopAnimationAction.prototype.serialize = function (parent) {
  44211. return _super.prototype._serialize.call(this, {
  44212. name: "StopAnimationAction",
  44213. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  44214. }, parent);
  44215. };
  44216. return StopAnimationAction;
  44217. }(BABYLON.Action));
  44218. BABYLON.StopAnimationAction = StopAnimationAction;
  44219. var DoNothingAction = /** @class */ (function (_super) {
  44220. __extends(DoNothingAction, _super);
  44221. function DoNothingAction(triggerOptions, condition) {
  44222. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  44223. return _super.call(this, triggerOptions, condition) || this;
  44224. }
  44225. DoNothingAction.prototype.execute = function () {
  44226. };
  44227. DoNothingAction.prototype.serialize = function (parent) {
  44228. return _super.prototype._serialize.call(this, {
  44229. name: "DoNothingAction",
  44230. properties: []
  44231. }, parent);
  44232. };
  44233. return DoNothingAction;
  44234. }(BABYLON.Action));
  44235. BABYLON.DoNothingAction = DoNothingAction;
  44236. var CombineAction = /** @class */ (function (_super) {
  44237. __extends(CombineAction, _super);
  44238. function CombineAction(triggerOptions, children, condition) {
  44239. var _this = _super.call(this, triggerOptions, condition) || this;
  44240. _this.children = children;
  44241. return _this;
  44242. }
  44243. CombineAction.prototype._prepare = function () {
  44244. for (var index = 0; index < this.children.length; index++) {
  44245. this.children[index]._actionManager = this._actionManager;
  44246. this.children[index]._prepare();
  44247. }
  44248. };
  44249. CombineAction.prototype.execute = function (evt) {
  44250. for (var index = 0; index < this.children.length; index++) {
  44251. this.children[index].execute(evt);
  44252. }
  44253. };
  44254. CombineAction.prototype.serialize = function (parent) {
  44255. var serializationObject = _super.prototype._serialize.call(this, {
  44256. name: "CombineAction",
  44257. properties: [],
  44258. combine: []
  44259. }, parent);
  44260. for (var i = 0; i < this.children.length; i++) {
  44261. serializationObject.combine.push(this.children[i].serialize(null));
  44262. }
  44263. return serializationObject;
  44264. };
  44265. return CombineAction;
  44266. }(BABYLON.Action));
  44267. BABYLON.CombineAction = CombineAction;
  44268. var ExecuteCodeAction = /** @class */ (function (_super) {
  44269. __extends(ExecuteCodeAction, _super);
  44270. function ExecuteCodeAction(triggerOptions, func, condition) {
  44271. var _this = _super.call(this, triggerOptions, condition) || this;
  44272. _this.func = func;
  44273. return _this;
  44274. }
  44275. ExecuteCodeAction.prototype.execute = function (evt) {
  44276. this.func(evt);
  44277. };
  44278. return ExecuteCodeAction;
  44279. }(BABYLON.Action));
  44280. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  44281. var SetParentAction = /** @class */ (function (_super) {
  44282. __extends(SetParentAction, _super);
  44283. function SetParentAction(triggerOptions, target, parent, condition) {
  44284. var _this = _super.call(this, triggerOptions, condition) || this;
  44285. _this._target = target;
  44286. _this._parent = parent;
  44287. return _this;
  44288. }
  44289. SetParentAction.prototype._prepare = function () {
  44290. };
  44291. SetParentAction.prototype.execute = function () {
  44292. if (this._target.parent === this._parent) {
  44293. return;
  44294. }
  44295. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  44296. invertParentWorldMatrix.invert();
  44297. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  44298. this._target.parent = this._parent;
  44299. };
  44300. SetParentAction.prototype.serialize = function (parent) {
  44301. return _super.prototype._serialize.call(this, {
  44302. name: "SetParentAction",
  44303. properties: [
  44304. BABYLON.Action._GetTargetProperty(this._target),
  44305. BABYLON.Action._GetTargetProperty(this._parent),
  44306. ]
  44307. }, parent);
  44308. };
  44309. return SetParentAction;
  44310. }(BABYLON.Action));
  44311. BABYLON.SetParentAction = SetParentAction;
  44312. var PlaySoundAction = /** @class */ (function (_super) {
  44313. __extends(PlaySoundAction, _super);
  44314. function PlaySoundAction(triggerOptions, sound, condition) {
  44315. var _this = _super.call(this, triggerOptions, condition) || this;
  44316. _this._sound = sound;
  44317. return _this;
  44318. }
  44319. PlaySoundAction.prototype._prepare = function () {
  44320. };
  44321. PlaySoundAction.prototype.execute = function () {
  44322. if (this._sound !== undefined)
  44323. this._sound.play();
  44324. };
  44325. PlaySoundAction.prototype.serialize = function (parent) {
  44326. return _super.prototype._serialize.call(this, {
  44327. name: "PlaySoundAction",
  44328. properties: [{ name: "sound", value: this._sound.name }]
  44329. }, parent);
  44330. };
  44331. return PlaySoundAction;
  44332. }(BABYLON.Action));
  44333. BABYLON.PlaySoundAction = PlaySoundAction;
  44334. var StopSoundAction = /** @class */ (function (_super) {
  44335. __extends(StopSoundAction, _super);
  44336. function StopSoundAction(triggerOptions, sound, condition) {
  44337. var _this = _super.call(this, triggerOptions, condition) || this;
  44338. _this._sound = sound;
  44339. return _this;
  44340. }
  44341. StopSoundAction.prototype._prepare = function () {
  44342. };
  44343. StopSoundAction.prototype.execute = function () {
  44344. if (this._sound !== undefined)
  44345. this._sound.stop();
  44346. };
  44347. StopSoundAction.prototype.serialize = function (parent) {
  44348. return _super.prototype._serialize.call(this, {
  44349. name: "StopSoundAction",
  44350. properties: [{ name: "sound", value: this._sound.name }]
  44351. }, parent);
  44352. };
  44353. return StopSoundAction;
  44354. }(BABYLON.Action));
  44355. BABYLON.StopSoundAction = StopSoundAction;
  44356. })(BABYLON || (BABYLON = {}));
  44357. //# sourceMappingURL=babylon.directActions.js.map
  44358. var BABYLON;
  44359. (function (BABYLON) {
  44360. var SpriteManager = /** @class */ (function () {
  44361. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  44362. if (epsilon === void 0) { epsilon = 0.01; }
  44363. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44364. this.name = name;
  44365. this.sprites = new Array();
  44366. this.renderingGroupId = 0;
  44367. this.layerMask = 0x0FFFFFFF;
  44368. this.fogEnabled = true;
  44369. this.isPickable = false;
  44370. /**
  44371. * An event triggered when the manager is disposed.
  44372. * @type {BABYLON.Observable}
  44373. */
  44374. this.onDisposeObservable = new BABYLON.Observable();
  44375. this._vertexBuffers = {};
  44376. this._capacity = capacity;
  44377. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  44378. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44379. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44380. if (cellSize.width && cellSize.height) {
  44381. this.cellWidth = cellSize.width;
  44382. this.cellHeight = cellSize.height;
  44383. }
  44384. else if (cellSize !== undefined) {
  44385. this.cellWidth = cellSize;
  44386. this.cellHeight = cellSize;
  44387. }
  44388. else {
  44389. return;
  44390. }
  44391. this._epsilon = epsilon;
  44392. this._scene = scene;
  44393. this._scene.spriteManagers.push(this);
  44394. var indices = [];
  44395. var index = 0;
  44396. for (var count = 0; count < capacity; count++) {
  44397. indices.push(index);
  44398. indices.push(index + 1);
  44399. indices.push(index + 2);
  44400. indices.push(index);
  44401. indices.push(index + 2);
  44402. indices.push(index + 3);
  44403. index += 4;
  44404. }
  44405. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  44406. // VBO
  44407. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  44408. this._vertexData = new Float32Array(capacity * 16 * 4);
  44409. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  44410. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  44411. var options = this._buffer.createVertexBuffer("options", 4, 4);
  44412. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  44413. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  44414. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  44415. this._vertexBuffers["options"] = options;
  44416. this._vertexBuffers["cellInfo"] = cellInfo;
  44417. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  44418. // Effects
  44419. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  44420. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  44421. }
  44422. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  44423. set: function (callback) {
  44424. if (this._onDisposeObserver) {
  44425. this.onDisposeObservable.remove(this._onDisposeObserver);
  44426. }
  44427. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  44428. },
  44429. enumerable: true,
  44430. configurable: true
  44431. });
  44432. Object.defineProperty(SpriteManager.prototype, "texture", {
  44433. get: function () {
  44434. return this._spriteTexture;
  44435. },
  44436. set: function (value) {
  44437. this._spriteTexture = value;
  44438. },
  44439. enumerable: true,
  44440. configurable: true
  44441. });
  44442. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  44443. var arrayOffset = index * 16;
  44444. if (offsetX === 0)
  44445. offsetX = this._epsilon;
  44446. else if (offsetX === 1)
  44447. offsetX = 1 - this._epsilon;
  44448. if (offsetY === 0)
  44449. offsetY = this._epsilon;
  44450. else if (offsetY === 1)
  44451. offsetY = 1 - this._epsilon;
  44452. this._vertexData[arrayOffset] = sprite.position.x;
  44453. this._vertexData[arrayOffset + 1] = sprite.position.y;
  44454. this._vertexData[arrayOffset + 2] = sprite.position.z;
  44455. this._vertexData[arrayOffset + 3] = sprite.angle;
  44456. this._vertexData[arrayOffset + 4] = sprite.width;
  44457. this._vertexData[arrayOffset + 5] = sprite.height;
  44458. this._vertexData[arrayOffset + 6] = offsetX;
  44459. this._vertexData[arrayOffset + 7] = offsetY;
  44460. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  44461. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  44462. var offset = (sprite.cellIndex / rowSize) >> 0;
  44463. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  44464. this._vertexData[arrayOffset + 11] = offset;
  44465. // Color
  44466. this._vertexData[arrayOffset + 12] = sprite.color.r;
  44467. this._vertexData[arrayOffset + 13] = sprite.color.g;
  44468. this._vertexData[arrayOffset + 14] = sprite.color.b;
  44469. this._vertexData[arrayOffset + 15] = sprite.color.a;
  44470. };
  44471. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  44472. var count = Math.min(this._capacity, this.sprites.length);
  44473. var min = BABYLON.Vector3.Zero();
  44474. var max = BABYLON.Vector3.Zero();
  44475. var distance = Number.MAX_VALUE;
  44476. var currentSprite = null;
  44477. var cameraSpacePosition = BABYLON.Vector3.Zero();
  44478. var cameraView = camera.getViewMatrix();
  44479. for (var index = 0; index < count; index++) {
  44480. var sprite = this.sprites[index];
  44481. if (!sprite) {
  44482. continue;
  44483. }
  44484. if (predicate) {
  44485. if (!predicate(sprite)) {
  44486. continue;
  44487. }
  44488. }
  44489. else if (!sprite.isPickable) {
  44490. continue;
  44491. }
  44492. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  44493. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  44494. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  44495. if (ray.intersectsBoxMinMax(min, max)) {
  44496. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  44497. if (distance > currentDistance) {
  44498. distance = currentDistance;
  44499. currentSprite = sprite;
  44500. if (fastCheck) {
  44501. break;
  44502. }
  44503. }
  44504. }
  44505. }
  44506. if (currentSprite) {
  44507. var result = new BABYLON.PickingInfo();
  44508. result.hit = true;
  44509. result.pickedSprite = currentSprite;
  44510. result.distance = distance;
  44511. return result;
  44512. }
  44513. return null;
  44514. };
  44515. SpriteManager.prototype.render = function () {
  44516. // Check
  44517. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  44518. return;
  44519. var engine = this._scene.getEngine();
  44520. var baseSize = this._spriteTexture.getBaseSize();
  44521. // Sprites
  44522. var deltaTime = engine.getDeltaTime();
  44523. var max = Math.min(this._capacity, this.sprites.length);
  44524. var rowSize = baseSize.width / this.cellWidth;
  44525. var offset = 0;
  44526. for (var index = 0; index < max; index++) {
  44527. var sprite = this.sprites[index];
  44528. if (!sprite) {
  44529. continue;
  44530. }
  44531. sprite._animate(deltaTime);
  44532. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  44533. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  44534. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  44535. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  44536. }
  44537. this._buffer.update(this._vertexData);
  44538. // Render
  44539. var effect = this._effectBase;
  44540. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  44541. effect = this._effectFog;
  44542. }
  44543. engine.enableEffect(effect);
  44544. var viewMatrix = this._scene.getViewMatrix();
  44545. effect.setTexture("diffuseSampler", this._spriteTexture);
  44546. effect.setMatrix("view", viewMatrix);
  44547. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  44548. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  44549. // Fog
  44550. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  44551. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  44552. effect.setColor3("vFogColor", this._scene.fogColor);
  44553. }
  44554. // VBOs
  44555. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  44556. // Draw order
  44557. engine.setDepthFunctionToLessOrEqual();
  44558. effect.setBool("alphaTest", true);
  44559. engine.setColorWrite(false);
  44560. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  44561. engine.setColorWrite(true);
  44562. effect.setBool("alphaTest", false);
  44563. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  44564. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  44565. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  44566. };
  44567. SpriteManager.prototype.dispose = function () {
  44568. if (this._buffer) {
  44569. this._buffer.dispose();
  44570. this._buffer = null;
  44571. }
  44572. if (this._indexBuffer) {
  44573. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  44574. this._indexBuffer = null;
  44575. }
  44576. if (this._spriteTexture) {
  44577. this._spriteTexture.dispose();
  44578. this._spriteTexture = null;
  44579. }
  44580. // Remove from scene
  44581. var index = this._scene.spriteManagers.indexOf(this);
  44582. this._scene.spriteManagers.splice(index, 1);
  44583. // Callback
  44584. this.onDisposeObservable.notifyObservers(this);
  44585. this.onDisposeObservable.clear();
  44586. };
  44587. return SpriteManager;
  44588. }());
  44589. BABYLON.SpriteManager = SpriteManager;
  44590. })(BABYLON || (BABYLON = {}));
  44591. //# sourceMappingURL=babylon.spriteManager.js.map
  44592. var BABYLON;
  44593. (function (BABYLON) {
  44594. var Sprite = /** @class */ (function () {
  44595. function Sprite(name, manager) {
  44596. this.name = name;
  44597. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  44598. this.width = 1.0;
  44599. this.height = 1.0;
  44600. this.angle = 0;
  44601. this.cellIndex = 0;
  44602. this.invertU = 0;
  44603. this.invertV = 0;
  44604. this.animations = new Array();
  44605. this.isPickable = false;
  44606. this._animationStarted = false;
  44607. this._loopAnimation = false;
  44608. this._fromIndex = 0;
  44609. this._toIndex = 0;
  44610. this._delay = 0;
  44611. this._direction = 1;
  44612. this._time = 0;
  44613. this._manager = manager;
  44614. this._manager.sprites.push(this);
  44615. this.position = BABYLON.Vector3.Zero();
  44616. }
  44617. Object.defineProperty(Sprite.prototype, "size", {
  44618. get: function () {
  44619. return this.width;
  44620. },
  44621. set: function (value) {
  44622. this.width = value;
  44623. this.height = value;
  44624. },
  44625. enumerable: true,
  44626. configurable: true
  44627. });
  44628. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  44629. this._fromIndex = from;
  44630. this._toIndex = to;
  44631. this._loopAnimation = loop;
  44632. this._delay = delay;
  44633. this._animationStarted = true;
  44634. this._direction = from < to ? 1 : -1;
  44635. this.cellIndex = from;
  44636. this._time = 0;
  44637. this._onAnimationEnd = onAnimationEnd;
  44638. };
  44639. Sprite.prototype.stopAnimation = function () {
  44640. this._animationStarted = false;
  44641. };
  44642. Sprite.prototype._animate = function (deltaTime) {
  44643. if (!this._animationStarted)
  44644. return;
  44645. this._time += deltaTime;
  44646. if (this._time > this._delay) {
  44647. this._time = this._time % this._delay;
  44648. this.cellIndex += this._direction;
  44649. if (this.cellIndex > this._toIndex) {
  44650. if (this._loopAnimation) {
  44651. this.cellIndex = this._fromIndex;
  44652. }
  44653. else {
  44654. this.cellIndex = this._toIndex;
  44655. this._animationStarted = false;
  44656. if (this._onAnimationEnd) {
  44657. this._onAnimationEnd();
  44658. }
  44659. if (this.disposeWhenFinishedAnimating) {
  44660. this.dispose();
  44661. }
  44662. }
  44663. }
  44664. }
  44665. };
  44666. Sprite.prototype.dispose = function () {
  44667. for (var i = 0; i < this._manager.sprites.length; i++) {
  44668. if (this._manager.sprites[i] == this) {
  44669. this._manager.sprites.splice(i, 1);
  44670. }
  44671. }
  44672. };
  44673. return Sprite;
  44674. }());
  44675. BABYLON.Sprite = Sprite;
  44676. })(BABYLON || (BABYLON = {}));
  44677. //# sourceMappingURL=babylon.sprite.js.map
  44678. var BABYLON;
  44679. (function (BABYLON) {
  44680. var IntersectionInfo = /** @class */ (function () {
  44681. function IntersectionInfo(bu, bv, distance) {
  44682. this.bu = bu;
  44683. this.bv = bv;
  44684. this.distance = distance;
  44685. this.faceId = 0;
  44686. this.subMeshId = 0;
  44687. }
  44688. return IntersectionInfo;
  44689. }());
  44690. BABYLON.IntersectionInfo = IntersectionInfo;
  44691. var PickingInfo = /** @class */ (function () {
  44692. function PickingInfo() {
  44693. this.hit = false;
  44694. this.distance = 0;
  44695. this.pickedPoint = null;
  44696. this.pickedMesh = null;
  44697. this.bu = 0;
  44698. this.bv = 0;
  44699. this.faceId = -1;
  44700. this.subMeshId = 0;
  44701. this.pickedSprite = null;
  44702. }
  44703. // Methods
  44704. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  44705. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  44706. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  44707. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44708. return null;
  44709. }
  44710. var indices = this.pickedMesh.getIndices();
  44711. if (!indices) {
  44712. return null;
  44713. }
  44714. var result;
  44715. if (useVerticesNormals) {
  44716. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  44717. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  44718. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  44719. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  44720. normal0 = normal0.scale(this.bu);
  44721. normal1 = normal1.scale(this.bv);
  44722. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  44723. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  44724. }
  44725. else {
  44726. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  44727. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  44728. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  44729. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  44730. var p1p2 = vertex1.subtract(vertex2);
  44731. var p3p2 = vertex3.subtract(vertex2);
  44732. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  44733. }
  44734. if (useWorldCoordinates) {
  44735. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  44736. }
  44737. return BABYLON.Vector3.Normalize(result);
  44738. };
  44739. PickingInfo.prototype.getTextureCoordinates = function () {
  44740. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  44741. return null;
  44742. }
  44743. var indices = this.pickedMesh.getIndices();
  44744. if (!indices) {
  44745. return null;
  44746. }
  44747. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  44748. if (!uvs) {
  44749. return null;
  44750. }
  44751. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  44752. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  44753. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  44754. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  44755. uv1 = uv1.scale(this.bu);
  44756. uv2 = uv2.scale(this.bv);
  44757. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  44758. };
  44759. return PickingInfo;
  44760. }());
  44761. BABYLON.PickingInfo = PickingInfo;
  44762. })(BABYLON || (BABYLON = {}));
  44763. //# sourceMappingURL=babylon.pickingInfo.js.map
  44764. var BABYLON;
  44765. (function (BABYLON) {
  44766. var Ray = /** @class */ (function () {
  44767. function Ray(origin, direction, length) {
  44768. if (length === void 0) { length = Number.MAX_VALUE; }
  44769. this.origin = origin;
  44770. this.direction = direction;
  44771. this.length = length;
  44772. }
  44773. // Methods
  44774. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  44775. var d = 0.0;
  44776. var maxValue = Number.MAX_VALUE;
  44777. var inv;
  44778. var min;
  44779. var max;
  44780. var temp;
  44781. if (Math.abs(this.direction.x) < 0.0000001) {
  44782. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  44783. return false;
  44784. }
  44785. }
  44786. else {
  44787. inv = 1.0 / this.direction.x;
  44788. min = (minimum.x - this.origin.x) * inv;
  44789. max = (maximum.x - this.origin.x) * inv;
  44790. if (max === -Infinity) {
  44791. max = Infinity;
  44792. }
  44793. if (min > max) {
  44794. temp = min;
  44795. min = max;
  44796. max = temp;
  44797. }
  44798. d = Math.max(min, d);
  44799. maxValue = Math.min(max, maxValue);
  44800. if (d > maxValue) {
  44801. return false;
  44802. }
  44803. }
  44804. if (Math.abs(this.direction.y) < 0.0000001) {
  44805. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  44806. return false;
  44807. }
  44808. }
  44809. else {
  44810. inv = 1.0 / this.direction.y;
  44811. min = (minimum.y - this.origin.y) * inv;
  44812. max = (maximum.y - this.origin.y) * inv;
  44813. if (max === -Infinity) {
  44814. max = Infinity;
  44815. }
  44816. if (min > max) {
  44817. temp = min;
  44818. min = max;
  44819. max = temp;
  44820. }
  44821. d = Math.max(min, d);
  44822. maxValue = Math.min(max, maxValue);
  44823. if (d > maxValue) {
  44824. return false;
  44825. }
  44826. }
  44827. if (Math.abs(this.direction.z) < 0.0000001) {
  44828. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  44829. return false;
  44830. }
  44831. }
  44832. else {
  44833. inv = 1.0 / this.direction.z;
  44834. min = (minimum.z - this.origin.z) * inv;
  44835. max = (maximum.z - this.origin.z) * inv;
  44836. if (max === -Infinity) {
  44837. max = Infinity;
  44838. }
  44839. if (min > max) {
  44840. temp = min;
  44841. min = max;
  44842. max = temp;
  44843. }
  44844. d = Math.max(min, d);
  44845. maxValue = Math.min(max, maxValue);
  44846. if (d > maxValue) {
  44847. return false;
  44848. }
  44849. }
  44850. return true;
  44851. };
  44852. Ray.prototype.intersectsBox = function (box) {
  44853. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  44854. };
  44855. Ray.prototype.intersectsSphere = function (sphere) {
  44856. var x = sphere.center.x - this.origin.x;
  44857. var y = sphere.center.y - this.origin.y;
  44858. var z = sphere.center.z - this.origin.z;
  44859. var pyth = (x * x) + (y * y) + (z * z);
  44860. var rr = sphere.radius * sphere.radius;
  44861. if (pyth <= rr) {
  44862. return true;
  44863. }
  44864. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  44865. if (dot < 0.0) {
  44866. return false;
  44867. }
  44868. var temp = pyth - (dot * dot);
  44869. return temp <= rr;
  44870. };
  44871. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  44872. if (!this._edge1) {
  44873. this._edge1 = BABYLON.Vector3.Zero();
  44874. this._edge2 = BABYLON.Vector3.Zero();
  44875. this._pvec = BABYLON.Vector3.Zero();
  44876. this._tvec = BABYLON.Vector3.Zero();
  44877. this._qvec = BABYLON.Vector3.Zero();
  44878. }
  44879. vertex1.subtractToRef(vertex0, this._edge1);
  44880. vertex2.subtractToRef(vertex0, this._edge2);
  44881. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  44882. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  44883. if (det === 0) {
  44884. return null;
  44885. }
  44886. var invdet = 1 / det;
  44887. this.origin.subtractToRef(vertex0, this._tvec);
  44888. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  44889. if (bu < 0 || bu > 1.0) {
  44890. return null;
  44891. }
  44892. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  44893. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  44894. if (bv < 0 || bu + bv > 1.0) {
  44895. return null;
  44896. }
  44897. //check if the distance is longer than the predefined length.
  44898. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  44899. if (distance > this.length) {
  44900. return null;
  44901. }
  44902. return new BABYLON.IntersectionInfo(bu, bv, distance);
  44903. };
  44904. Ray.prototype.intersectsPlane = function (plane) {
  44905. var distance;
  44906. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  44907. if (Math.abs(result1) < 9.99999997475243E-07) {
  44908. return null;
  44909. }
  44910. else {
  44911. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  44912. distance = (-plane.d - result2) / result1;
  44913. if (distance < 0.0) {
  44914. if (distance < -9.99999997475243E-07) {
  44915. return null;
  44916. }
  44917. else {
  44918. return 0;
  44919. }
  44920. }
  44921. return distance;
  44922. }
  44923. };
  44924. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  44925. var tm = BABYLON.Tmp.Matrix[0];
  44926. mesh.getWorldMatrix().invertToRef(tm);
  44927. if (this._tmpRay) {
  44928. Ray.TransformToRef(this, tm, this._tmpRay);
  44929. }
  44930. else {
  44931. this._tmpRay = Ray.Transform(this, tm);
  44932. }
  44933. return mesh.intersects(this._tmpRay, fastCheck);
  44934. };
  44935. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  44936. if (results) {
  44937. results.length = 0;
  44938. }
  44939. else {
  44940. results = [];
  44941. }
  44942. for (var i = 0; i < meshes.length; i++) {
  44943. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  44944. if (pickInfo.hit) {
  44945. results.push(pickInfo);
  44946. }
  44947. }
  44948. results.sort(this._comparePickingInfo);
  44949. return results;
  44950. };
  44951. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  44952. if (pickingInfoA.distance < pickingInfoB.distance) {
  44953. return -1;
  44954. }
  44955. else if (pickingInfoA.distance > pickingInfoB.distance) {
  44956. return 1;
  44957. }
  44958. else {
  44959. return 0;
  44960. }
  44961. };
  44962. /**
  44963. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  44964. * @param sega the first point of the segment to test the intersection against
  44965. * @param segb the second point of the segment to test the intersection against
  44966. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  44967. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  44968. */
  44969. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  44970. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  44971. var u = segb.subtract(sega);
  44972. var v = rsegb.subtract(this.origin);
  44973. var w = sega.subtract(this.origin);
  44974. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  44975. var b = BABYLON.Vector3.Dot(u, v);
  44976. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  44977. var d = BABYLON.Vector3.Dot(u, w);
  44978. var e = BABYLON.Vector3.Dot(v, w);
  44979. var D = a * c - b * b; // always >= 0
  44980. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  44981. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  44982. // compute the line parameters of the two closest points
  44983. if (D < Ray.smallnum) {
  44984. sN = 0.0; // force using point P0 on segment S1
  44985. sD = 1.0; // to prevent possible division by 0.0 later
  44986. tN = e;
  44987. tD = c;
  44988. }
  44989. else {
  44990. sN = (b * e - c * d);
  44991. tN = (a * e - b * d);
  44992. if (sN < 0.0) {
  44993. sN = 0.0;
  44994. tN = e;
  44995. tD = c;
  44996. }
  44997. else if (sN > sD) {
  44998. sN = sD;
  44999. tN = e + b;
  45000. tD = c;
  45001. }
  45002. }
  45003. if (tN < 0.0) {
  45004. tN = 0.0;
  45005. // recompute sc for this edge
  45006. if (-d < 0.0) {
  45007. sN = 0.0;
  45008. }
  45009. else if (-d > a)
  45010. sN = sD;
  45011. else {
  45012. sN = -d;
  45013. sD = a;
  45014. }
  45015. }
  45016. else if (tN > tD) {
  45017. tN = tD;
  45018. // recompute sc for this edge
  45019. if ((-d + b) < 0.0) {
  45020. sN = 0;
  45021. }
  45022. else if ((-d + b) > a) {
  45023. sN = sD;
  45024. }
  45025. else {
  45026. sN = (-d + b);
  45027. sD = a;
  45028. }
  45029. }
  45030. // finally do the division to get sc and tc
  45031. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  45032. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  45033. // get the difference of the two closest points
  45034. var qtc = v.multiplyByFloats(tc, tc, tc);
  45035. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  45036. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  45037. if (isIntersected) {
  45038. return qtc.length();
  45039. }
  45040. return -1;
  45041. };
  45042. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  45043. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  45044. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  45045. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  45046. this.direction.normalize();
  45047. return this;
  45048. };
  45049. // Statics
  45050. Ray.Zero = function () {
  45051. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  45052. };
  45053. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  45054. var result = Ray.Zero();
  45055. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  45056. };
  45057. /**
  45058. * 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
  45059. * transformed to the given world matrix.
  45060. * @param origin The origin point
  45061. * @param end The end point
  45062. * @param world a matrix to transform the ray to. Default is the identity matrix.
  45063. */
  45064. Ray.CreateNewFromTo = function (origin, end, world) {
  45065. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  45066. var direction = end.subtract(origin);
  45067. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  45068. direction.normalize();
  45069. return Ray.Transform(new Ray(origin, direction, length), world);
  45070. };
  45071. Ray.Transform = function (ray, matrix) {
  45072. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  45073. Ray.TransformToRef(ray, matrix, result);
  45074. return result;
  45075. };
  45076. Ray.TransformToRef = function (ray, matrix, result) {
  45077. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  45078. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  45079. result.length = ray.length;
  45080. var dir = result.direction;
  45081. var len = dir.length();
  45082. if (!(len === 0 || len === 1)) {
  45083. var num = 1.0 / len;
  45084. dir.x *= num;
  45085. dir.y *= num;
  45086. dir.z *= num;
  45087. result.length *= len;
  45088. }
  45089. };
  45090. Ray.smallnum = 0.00000001;
  45091. Ray.rayl = 10e8;
  45092. return Ray;
  45093. }());
  45094. BABYLON.Ray = Ray;
  45095. })(BABYLON || (BABYLON = {}));
  45096. //# sourceMappingURL=babylon.ray.js.map
  45097. var BABYLON;
  45098. (function (BABYLON) {
  45099. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  45100. if (boxMin.x > sphereCenter.x + sphereRadius)
  45101. return false;
  45102. if (sphereCenter.x - sphereRadius > boxMax.x)
  45103. return false;
  45104. if (boxMin.y > sphereCenter.y + sphereRadius)
  45105. return false;
  45106. if (sphereCenter.y - sphereRadius > boxMax.y)
  45107. return false;
  45108. if (boxMin.z > sphereCenter.z + sphereRadius)
  45109. return false;
  45110. if (sphereCenter.z - sphereRadius > boxMax.z)
  45111. return false;
  45112. return true;
  45113. };
  45114. var getLowestRoot = (function () {
  45115. var result = { root: 0, found: false };
  45116. return function (a, b, c, maxR) {
  45117. result.root = 0;
  45118. result.found = false;
  45119. var determinant = b * b - 4.0 * a * c;
  45120. if (determinant < 0)
  45121. return result;
  45122. var sqrtD = Math.sqrt(determinant);
  45123. var r1 = (-b - sqrtD) / (2.0 * a);
  45124. var r2 = (-b + sqrtD) / (2.0 * a);
  45125. if (r1 > r2) {
  45126. var temp = r2;
  45127. r2 = r1;
  45128. r1 = temp;
  45129. }
  45130. if (r1 > 0 && r1 < maxR) {
  45131. result.root = r1;
  45132. result.found = true;
  45133. return result;
  45134. }
  45135. if (r2 > 0 && r2 < maxR) {
  45136. result.root = r2;
  45137. result.found = true;
  45138. return result;
  45139. }
  45140. return result;
  45141. };
  45142. })();
  45143. var Collider = /** @class */ (function () {
  45144. function Collider() {
  45145. this._collisionPoint = BABYLON.Vector3.Zero();
  45146. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  45147. this._tempVector = BABYLON.Vector3.Zero();
  45148. this._tempVector2 = BABYLON.Vector3.Zero();
  45149. this._tempVector3 = BABYLON.Vector3.Zero();
  45150. this._tempVector4 = BABYLON.Vector3.Zero();
  45151. this._edge = BABYLON.Vector3.Zero();
  45152. this._baseToVertex = BABYLON.Vector3.Zero();
  45153. this._destinationPoint = BABYLON.Vector3.Zero();
  45154. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  45155. this._displacementVector = BABYLON.Vector3.Zero();
  45156. this._radius = BABYLON.Vector3.One();
  45157. this._retry = 0;
  45158. this._basePointWorld = BABYLON.Vector3.Zero();
  45159. this._velocityWorld = BABYLON.Vector3.Zero();
  45160. this._normalizedVelocity = BABYLON.Vector3.Zero();
  45161. this._collisionMask = -1;
  45162. }
  45163. Object.defineProperty(Collider.prototype, "collisionMask", {
  45164. get: function () {
  45165. return this._collisionMask;
  45166. },
  45167. set: function (mask) {
  45168. this._collisionMask = !isNaN(mask) ? mask : -1;
  45169. },
  45170. enumerable: true,
  45171. configurable: true
  45172. });
  45173. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  45174. /**
  45175. * Gets the plane normal used to compute the sliding response (in local space)
  45176. */
  45177. get: function () {
  45178. return this._slidePlaneNormal;
  45179. },
  45180. enumerable: true,
  45181. configurable: true
  45182. });
  45183. // Methods
  45184. Collider.prototype._initialize = function (source, dir, e) {
  45185. this._velocity = dir;
  45186. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  45187. this._basePoint = source;
  45188. source.multiplyToRef(this._radius, this._basePointWorld);
  45189. dir.multiplyToRef(this._radius, this._velocityWorld);
  45190. this._velocityWorldLength = this._velocityWorld.length();
  45191. this._epsilon = e;
  45192. this.collisionFound = false;
  45193. };
  45194. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  45195. pa.subtractToRef(point, this._tempVector);
  45196. pb.subtractToRef(point, this._tempVector2);
  45197. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  45198. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  45199. if (d < 0)
  45200. return false;
  45201. pc.subtractToRef(point, this._tempVector3);
  45202. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  45203. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  45204. if (d < 0)
  45205. return false;
  45206. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  45207. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  45208. return d >= 0;
  45209. };
  45210. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  45211. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  45212. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  45213. if (distance > this._velocityWorldLength + max + sphereRadius) {
  45214. return false;
  45215. }
  45216. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  45217. return false;
  45218. return true;
  45219. };
  45220. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  45221. var t0;
  45222. var embeddedInPlane = false;
  45223. //defensive programming, actually not needed.
  45224. if (!trianglePlaneArray) {
  45225. trianglePlaneArray = [];
  45226. }
  45227. if (!trianglePlaneArray[faceIndex]) {
  45228. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  45229. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  45230. }
  45231. var trianglePlane = trianglePlaneArray[faceIndex];
  45232. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  45233. return;
  45234. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  45235. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  45236. if (normalDotVelocity == 0) {
  45237. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  45238. return;
  45239. embeddedInPlane = true;
  45240. t0 = 0;
  45241. }
  45242. else {
  45243. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  45244. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  45245. if (t0 > t1) {
  45246. var temp = t1;
  45247. t1 = t0;
  45248. t0 = temp;
  45249. }
  45250. if (t0 > 1.0 || t1 < 0.0)
  45251. return;
  45252. if (t0 < 0)
  45253. t0 = 0;
  45254. if (t0 > 1.0)
  45255. t0 = 1.0;
  45256. }
  45257. this._collisionPoint.copyFromFloats(0, 0, 0);
  45258. var found = false;
  45259. var t = 1.0;
  45260. if (!embeddedInPlane) {
  45261. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  45262. this._velocity.scaleToRef(t0, this._tempVector);
  45263. this._planeIntersectionPoint.addInPlace(this._tempVector);
  45264. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  45265. found = true;
  45266. t = t0;
  45267. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  45268. }
  45269. }
  45270. if (!found) {
  45271. var velocitySquaredLength = this._velocity.lengthSquared();
  45272. var a = velocitySquaredLength;
  45273. this._basePoint.subtractToRef(p1, this._tempVector);
  45274. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  45275. var c = this._tempVector.lengthSquared() - 1.0;
  45276. var lowestRoot = getLowestRoot(a, b, c, t);
  45277. if (lowestRoot.found) {
  45278. t = lowestRoot.root;
  45279. found = true;
  45280. this._collisionPoint.copyFrom(p1);
  45281. }
  45282. this._basePoint.subtractToRef(p2, this._tempVector);
  45283. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  45284. c = this._tempVector.lengthSquared() - 1.0;
  45285. lowestRoot = getLowestRoot(a, b, c, t);
  45286. if (lowestRoot.found) {
  45287. t = lowestRoot.root;
  45288. found = true;
  45289. this._collisionPoint.copyFrom(p2);
  45290. }
  45291. this._basePoint.subtractToRef(p3, this._tempVector);
  45292. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  45293. c = this._tempVector.lengthSquared() - 1.0;
  45294. lowestRoot = getLowestRoot(a, b, c, t);
  45295. if (lowestRoot.found) {
  45296. t = lowestRoot.root;
  45297. found = true;
  45298. this._collisionPoint.copyFrom(p3);
  45299. }
  45300. p2.subtractToRef(p1, this._edge);
  45301. p1.subtractToRef(this._basePoint, this._baseToVertex);
  45302. var edgeSquaredLength = this._edge.lengthSquared();
  45303. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  45304. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  45305. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  45306. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  45307. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  45308. lowestRoot = getLowestRoot(a, b, c, t);
  45309. if (lowestRoot.found) {
  45310. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  45311. if (f >= 0.0 && f <= 1.0) {
  45312. t = lowestRoot.root;
  45313. found = true;
  45314. this._edge.scaleInPlace(f);
  45315. p1.addToRef(this._edge, this._collisionPoint);
  45316. }
  45317. }
  45318. p3.subtractToRef(p2, this._edge);
  45319. p2.subtractToRef(this._basePoint, this._baseToVertex);
  45320. edgeSquaredLength = this._edge.lengthSquared();
  45321. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  45322. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  45323. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  45324. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  45325. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  45326. lowestRoot = getLowestRoot(a, b, c, t);
  45327. if (lowestRoot.found) {
  45328. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  45329. if (f >= 0.0 && f <= 1.0) {
  45330. t = lowestRoot.root;
  45331. found = true;
  45332. this._edge.scaleInPlace(f);
  45333. p2.addToRef(this._edge, this._collisionPoint);
  45334. }
  45335. }
  45336. p1.subtractToRef(p3, this._edge);
  45337. p3.subtractToRef(this._basePoint, this._baseToVertex);
  45338. edgeSquaredLength = this._edge.lengthSquared();
  45339. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  45340. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  45341. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  45342. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  45343. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  45344. lowestRoot = getLowestRoot(a, b, c, t);
  45345. if (lowestRoot.found) {
  45346. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  45347. if (f >= 0.0 && f <= 1.0) {
  45348. t = lowestRoot.root;
  45349. found = true;
  45350. this._edge.scaleInPlace(f);
  45351. p3.addToRef(this._edge, this._collisionPoint);
  45352. }
  45353. }
  45354. }
  45355. if (found) {
  45356. var distToCollision = t * this._velocity.length();
  45357. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  45358. if (!this.intersectionPoint) {
  45359. this.intersectionPoint = this._collisionPoint.clone();
  45360. }
  45361. else {
  45362. this.intersectionPoint.copyFrom(this._collisionPoint);
  45363. }
  45364. this._nearestDistance = distToCollision;
  45365. this.collisionFound = true;
  45366. }
  45367. }
  45368. };
  45369. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  45370. for (var i = indexStart; i < indexEnd; i += 3) {
  45371. var p1 = pts[indices[i] - decal];
  45372. var p2 = pts[indices[i + 1] - decal];
  45373. var p3 = pts[indices[i + 2] - decal];
  45374. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  45375. }
  45376. };
  45377. Collider.prototype._getResponse = function (pos, vel) {
  45378. pos.addToRef(vel, this._destinationPoint);
  45379. vel.scaleInPlace((this._nearestDistance / vel.length()));
  45380. this._basePoint.addToRef(vel, pos);
  45381. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  45382. this._slidePlaneNormal.normalize();
  45383. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  45384. pos.addInPlace(this._displacementVector);
  45385. this.intersectionPoint.addInPlace(this._displacementVector);
  45386. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  45387. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  45388. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  45389. };
  45390. return Collider;
  45391. }());
  45392. BABYLON.Collider = Collider;
  45393. })(BABYLON || (BABYLON = {}));
  45394. //# sourceMappingURL=babylon.collider.js.map
  45395. var BABYLON;
  45396. (function (BABYLON) {
  45397. //WebWorker code will be inserted to this variable.
  45398. BABYLON.CollisionWorker = "";
  45399. var WorkerTaskType;
  45400. (function (WorkerTaskType) {
  45401. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  45402. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  45403. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  45404. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  45405. var WorkerReplyType;
  45406. (function (WorkerReplyType) {
  45407. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  45408. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  45409. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  45410. var CollisionCoordinatorWorker = /** @class */ (function () {
  45411. function CollisionCoordinatorWorker() {
  45412. var _this = this;
  45413. this._scaledPosition = BABYLON.Vector3.Zero();
  45414. this._scaledVelocity = BABYLON.Vector3.Zero();
  45415. this.onMeshUpdated = function (transformNode) {
  45416. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  45417. };
  45418. this.onGeometryUpdated = function (geometry) {
  45419. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  45420. };
  45421. this._afterRender = function () {
  45422. if (!_this._init)
  45423. return;
  45424. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  45425. return;
  45426. }
  45427. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  45428. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  45429. if (_this._runningUpdated > 4) {
  45430. return;
  45431. }
  45432. ++_this._runningUpdated;
  45433. var payload = {
  45434. updatedMeshes: _this._addUpdateMeshesList,
  45435. updatedGeometries: _this._addUpdateGeometriesList,
  45436. removedGeometries: _this._toRemoveGeometryArray,
  45437. removedMeshes: _this._toRemoveMeshesArray
  45438. };
  45439. var message = {
  45440. payload: payload,
  45441. taskType: WorkerTaskType.UPDATE
  45442. };
  45443. var serializable = [];
  45444. for (var id in payload.updatedGeometries) {
  45445. if (payload.updatedGeometries.hasOwnProperty(id)) {
  45446. //prepare transferables
  45447. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  45448. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  45449. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  45450. }
  45451. }
  45452. _this._worker.postMessage(message, serializable);
  45453. _this._addUpdateMeshesList = {};
  45454. _this._addUpdateGeometriesList = {};
  45455. _this._toRemoveGeometryArray = [];
  45456. _this._toRemoveMeshesArray = [];
  45457. };
  45458. this._onMessageFromWorker = function (e) {
  45459. var returnData = e.data;
  45460. if (returnData.error != WorkerReplyType.SUCCESS) {
  45461. //TODO what errors can be returned from the worker?
  45462. BABYLON.Tools.Warn("error returned from worker!");
  45463. return;
  45464. }
  45465. switch (returnData.taskType) {
  45466. case WorkerTaskType.INIT:
  45467. _this._init = true;
  45468. //Update the worked with ALL of the scene's current state
  45469. _this._scene.meshes.forEach(function (mesh) {
  45470. _this.onMeshAdded(mesh);
  45471. });
  45472. _this._scene.getGeometries().forEach(function (geometry) {
  45473. _this.onGeometryAdded(geometry);
  45474. });
  45475. break;
  45476. case WorkerTaskType.UPDATE:
  45477. _this._runningUpdated--;
  45478. break;
  45479. case WorkerTaskType.COLLIDE:
  45480. var returnPayload = returnData.payload;
  45481. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  45482. return;
  45483. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  45484. if (callback) {
  45485. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  45486. if (mesh) {
  45487. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  45488. }
  45489. }
  45490. //cleanup
  45491. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  45492. break;
  45493. }
  45494. };
  45495. this._collisionsCallbackArray = [];
  45496. this._init = false;
  45497. this._runningUpdated = 0;
  45498. this._addUpdateMeshesList = {};
  45499. this._addUpdateGeometriesList = {};
  45500. this._toRemoveGeometryArray = [];
  45501. this._toRemoveMeshesArray = [];
  45502. }
  45503. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  45504. if (!this._init)
  45505. return;
  45506. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  45507. return;
  45508. position.divideToRef(collider._radius, this._scaledPosition);
  45509. displacement.divideToRef(collider._radius, this._scaledVelocity);
  45510. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  45511. var payload = {
  45512. collider: {
  45513. position: this._scaledPosition.asArray(),
  45514. velocity: this._scaledVelocity.asArray(),
  45515. radius: collider._radius.asArray()
  45516. },
  45517. collisionId: collisionIndex,
  45518. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  45519. maximumRetry: maximumRetry
  45520. };
  45521. var message = {
  45522. payload: payload,
  45523. taskType: WorkerTaskType.COLLIDE
  45524. };
  45525. this._worker.postMessage(message);
  45526. };
  45527. CollisionCoordinatorWorker.prototype.init = function (scene) {
  45528. this._scene = scene;
  45529. this._scene.registerAfterRender(this._afterRender);
  45530. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  45531. this._worker = new Worker(workerUrl);
  45532. this._worker.onmessage = this._onMessageFromWorker;
  45533. var message = {
  45534. payload: {},
  45535. taskType: WorkerTaskType.INIT
  45536. };
  45537. this._worker.postMessage(message);
  45538. };
  45539. CollisionCoordinatorWorker.prototype.destroy = function () {
  45540. this._scene.unregisterAfterRender(this._afterRender);
  45541. this._worker.terminate();
  45542. };
  45543. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  45544. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  45545. this.onMeshUpdated(mesh);
  45546. };
  45547. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  45548. this._toRemoveMeshesArray.push(mesh.uniqueId);
  45549. };
  45550. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  45551. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  45552. geometry.onGeometryUpdated = this.onGeometryUpdated;
  45553. this.onGeometryUpdated(geometry);
  45554. };
  45555. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  45556. this._toRemoveGeometryArray.push(geometry.id);
  45557. };
  45558. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  45559. var submeshes = [];
  45560. if (mesh.subMeshes) {
  45561. submeshes = mesh.subMeshes.map(function (sm, idx) {
  45562. var boundingInfo = sm.getBoundingInfo();
  45563. return {
  45564. position: idx,
  45565. verticesStart: sm.verticesStart,
  45566. verticesCount: sm.verticesCount,
  45567. indexStart: sm.indexStart,
  45568. indexCount: sm.indexCount,
  45569. hasMaterial: !!sm.getMaterial(),
  45570. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  45571. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  45572. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  45573. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  45574. };
  45575. });
  45576. }
  45577. var geometryId = null;
  45578. if (mesh instanceof BABYLON.Mesh) {
  45579. var geometry = mesh.geometry;
  45580. geometryId = geometry ? geometry.id : null;
  45581. }
  45582. else if (mesh instanceof BABYLON.InstancedMesh) {
  45583. var geometry = mesh.sourceMesh.geometry;
  45584. geometryId = geometry ? geometry.id : null;
  45585. }
  45586. var boundingInfo = mesh.getBoundingInfo();
  45587. return {
  45588. uniqueId: mesh.uniqueId,
  45589. id: mesh.id,
  45590. name: mesh.name,
  45591. geometryId: geometryId,
  45592. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  45593. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  45594. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  45595. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  45596. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  45597. subMeshes: submeshes,
  45598. checkCollisions: mesh.checkCollisions
  45599. };
  45600. };
  45601. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  45602. return {
  45603. id: geometry.id,
  45604. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  45605. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  45606. indices: new Uint32Array(geometry.getIndices() || []),
  45607. };
  45608. };
  45609. return CollisionCoordinatorWorker;
  45610. }());
  45611. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  45612. var CollisionCoordinatorLegacy = /** @class */ (function () {
  45613. function CollisionCoordinatorLegacy() {
  45614. this._scaledPosition = BABYLON.Vector3.Zero();
  45615. this._scaledVelocity = BABYLON.Vector3.Zero();
  45616. this._finalPosition = BABYLON.Vector3.Zero();
  45617. }
  45618. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  45619. position.divideToRef(collider._radius, this._scaledPosition);
  45620. displacement.divideToRef(collider._radius, this._scaledVelocity);
  45621. collider.collidedMesh = null;
  45622. collider._retry = 0;
  45623. collider._initialVelocity = this._scaledVelocity;
  45624. collider._initialPosition = this._scaledPosition;
  45625. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  45626. this._finalPosition.multiplyInPlace(collider._radius);
  45627. //run the callback
  45628. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  45629. };
  45630. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  45631. this._scene = scene;
  45632. };
  45633. CollisionCoordinatorLegacy.prototype.destroy = function () {
  45634. //Legacy need no destruction method.
  45635. };
  45636. //No update in legacy mode
  45637. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  45638. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  45639. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  45640. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  45641. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  45642. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  45643. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  45644. if (excludedMesh === void 0) { excludedMesh = null; }
  45645. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  45646. if (collider._retry >= maximumRetry) {
  45647. finalPosition.copyFrom(position);
  45648. return;
  45649. }
  45650. // Check if this is a mesh else camera or -1
  45651. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  45652. collider._initialize(position, velocity, closeDistance);
  45653. // Check all meshes
  45654. for (var index = 0; index < this._scene.meshes.length; index++) {
  45655. var mesh = this._scene.meshes[index];
  45656. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  45657. mesh._checkCollision(collider);
  45658. }
  45659. }
  45660. if (!collider.collisionFound) {
  45661. position.addToRef(velocity, finalPosition);
  45662. return;
  45663. }
  45664. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  45665. collider._getResponse(position, velocity);
  45666. }
  45667. if (velocity.length() <= closeDistance) {
  45668. finalPosition.copyFrom(position);
  45669. return;
  45670. }
  45671. collider._retry++;
  45672. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  45673. };
  45674. return CollisionCoordinatorLegacy;
  45675. }());
  45676. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  45677. })(BABYLON || (BABYLON = {}));
  45678. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  45679. var BABYLON;
  45680. (function (BABYLON) {
  45681. var Particle = /** @class */ (function () {
  45682. function Particle(particleSystem) {
  45683. this.particleSystem = particleSystem;
  45684. this.position = BABYLON.Vector3.Zero();
  45685. this.direction = BABYLON.Vector3.Zero();
  45686. this.color = new BABYLON.Color4(0, 0, 0, 0);
  45687. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  45688. this.lifeTime = 1.0;
  45689. this.age = 0;
  45690. this.size = 0;
  45691. this.angle = 0;
  45692. this.angularSpeed = 0;
  45693. this._currentFrameCounter = 0;
  45694. this.cellIndex = 0;
  45695. if (!this.particleSystem.isAnimationSheetEnabled) {
  45696. return;
  45697. }
  45698. this.cellIndex = this.particleSystem.startSpriteCellID;
  45699. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  45700. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  45701. }
  45702. else {
  45703. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  45704. }
  45705. }
  45706. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  45707. // (ageOffset / scaledUpdateSpeed) / available cells
  45708. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  45709. this._currentFrameCounter += scaledUpdateSpeed;
  45710. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  45711. this._currentFrameCounter = 0;
  45712. this.cellIndex++;
  45713. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  45714. this.cellIndex = this.particleSystem.endSpriteCellID;
  45715. }
  45716. }
  45717. };
  45718. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  45719. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  45720. this.cellIndex++;
  45721. this._currentFrameCounter = 0;
  45722. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  45723. if (this.particleSystem.spriteCellLoop) {
  45724. this.cellIndex = this.particleSystem.startSpriteCellID;
  45725. }
  45726. else {
  45727. this.cellIndex = this.particleSystem.endSpriteCellID;
  45728. }
  45729. }
  45730. }
  45731. else {
  45732. this._currentFrameCounter++;
  45733. }
  45734. };
  45735. Particle.prototype.copyTo = function (other) {
  45736. other.position.copyFrom(this.position);
  45737. other.direction.copyFrom(this.direction);
  45738. other.color.copyFrom(this.color);
  45739. other.colorStep.copyFrom(this.colorStep);
  45740. other.lifeTime = this.lifeTime;
  45741. other.age = this.age;
  45742. other.size = this.size;
  45743. other.angle = this.angle;
  45744. other.angularSpeed = this.angularSpeed;
  45745. other.particleSystem = this.particleSystem;
  45746. other.cellIndex = this.cellIndex;
  45747. };
  45748. return Particle;
  45749. }());
  45750. BABYLON.Particle = Particle;
  45751. })(BABYLON || (BABYLON = {}));
  45752. //# sourceMappingURL=babylon.particle.js.map
  45753. var BABYLON;
  45754. (function (BABYLON) {
  45755. var ParticleSystem = /** @class */ (function () {
  45756. // end of sheet animation
  45757. function ParticleSystem(name, capacity, scene, customEffect, _isAnimationSheetEnabled, epsilon) {
  45758. if (customEffect === void 0) { customEffect = null; }
  45759. if (_isAnimationSheetEnabled === void 0) { _isAnimationSheetEnabled = false; }
  45760. if (epsilon === void 0) { epsilon = 0.01; }
  45761. var _this = this;
  45762. this.name = name;
  45763. this._isAnimationSheetEnabled = _isAnimationSheetEnabled;
  45764. // Members
  45765. this.animations = [];
  45766. this.renderingGroupId = 0;
  45767. this.emitter = null;
  45768. this.emitRate = 10;
  45769. this.manualEmitCount = -1;
  45770. this.updateSpeed = 0.01;
  45771. this.targetStopDuration = 0;
  45772. this.disposeOnStop = false;
  45773. this.minEmitPower = 1;
  45774. this.maxEmitPower = 1;
  45775. this.minLifeTime = 1;
  45776. this.maxLifeTime = 1;
  45777. this.minSize = 1;
  45778. this.maxSize = 1;
  45779. this.minAngularSpeed = 0;
  45780. this.maxAngularSpeed = 0;
  45781. this.layerMask = 0x0FFFFFFF;
  45782. this.customShader = null;
  45783. this.preventAutoStart = false;
  45784. /**
  45785. * An event triggered when the system is disposed.
  45786. * @type {BABYLON.Observable}
  45787. */
  45788. this.onDisposeObservable = new BABYLON.Observable();
  45789. this.onAnimationEnd = null;
  45790. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  45791. this.forceDepthWrite = false;
  45792. this.gravity = BABYLON.Vector3.Zero();
  45793. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  45794. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  45795. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  45796. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  45797. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  45798. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  45799. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  45800. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  45801. this.particles = new Array();
  45802. this._stockParticles = new Array();
  45803. this._newPartsExcess = 0;
  45804. this._vertexBuffers = {};
  45805. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  45806. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  45807. this._scaledDirection = BABYLON.Vector3.Zero();
  45808. this._scaledGravity = BABYLON.Vector3.Zero();
  45809. this._currentRenderId = -1;
  45810. this._started = false;
  45811. this._stopped = false;
  45812. this._actualFrame = 0;
  45813. // sheet animation
  45814. this.startSpriteCellID = 0;
  45815. this.endSpriteCellID = 0;
  45816. this.spriteCellLoop = true;
  45817. this.spriteCellChangeSpeed = 0;
  45818. this.spriteCellWidth = 0;
  45819. this.spriteCellHeight = 0;
  45820. this._vertexBufferSize = 11;
  45821. this.appendParticleVertexes = null;
  45822. this.id = name;
  45823. this._capacity = capacity;
  45824. this._epsilon = epsilon;
  45825. if (_isAnimationSheetEnabled) {
  45826. this._vertexBufferSize = 12;
  45827. }
  45828. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  45829. this._customEffect = customEffect;
  45830. scene.particleSystems.push(this);
  45831. this._createIndexBuffer();
  45832. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  45833. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  45834. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  45835. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  45836. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  45837. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  45838. if (this._isAnimationSheetEnabled) {
  45839. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  45840. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  45841. }
  45842. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  45843. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  45844. this._vertexBuffers["options"] = options;
  45845. // Default behaviors
  45846. this.particleEmitterType = new BABYLON.BoxParticleEmitter(this);
  45847. this.updateFunction = function (particles) {
  45848. for (var index = 0; index < particles.length; index++) {
  45849. var particle = particles[index];
  45850. particle.age += _this._scaledUpdateSpeed;
  45851. if (particle.age >= particle.lifeTime) {
  45852. _this.recycleParticle(particle);
  45853. index--;
  45854. continue;
  45855. }
  45856. else {
  45857. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  45858. particle.color.addInPlace(_this._scaledColorStep);
  45859. if (particle.color.a < 0)
  45860. particle.color.a = 0;
  45861. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  45862. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  45863. particle.position.addInPlace(_this._scaledDirection);
  45864. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  45865. particle.direction.addInPlace(_this._scaledGravity);
  45866. if (_this._isAnimationSheetEnabled) {
  45867. particle.updateCellIndex(_this._scaledUpdateSpeed);
  45868. }
  45869. }
  45870. }
  45871. };
  45872. }
  45873. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  45874. set: function (callback) {
  45875. if (this._onDisposeObserver) {
  45876. this.onDisposeObservable.remove(this._onDisposeObserver);
  45877. }
  45878. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  45879. },
  45880. enumerable: true,
  45881. configurable: true
  45882. });
  45883. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  45884. get: function () {
  45885. return this._isAnimationSheetEnabled;
  45886. },
  45887. enumerable: true,
  45888. configurable: true
  45889. });
  45890. ParticleSystem.prototype._createIndexBuffer = function () {
  45891. var indices = [];
  45892. var index = 0;
  45893. for (var count = 0; count < this._capacity; count++) {
  45894. indices.push(index);
  45895. indices.push(index + 1);
  45896. indices.push(index + 2);
  45897. indices.push(index);
  45898. indices.push(index + 2);
  45899. indices.push(index + 3);
  45900. index += 4;
  45901. }
  45902. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  45903. };
  45904. ParticleSystem.prototype.recycleParticle = function (particle) {
  45905. var lastParticle = this.particles.pop();
  45906. if (lastParticle !== particle) {
  45907. lastParticle.copyTo(particle);
  45908. this._stockParticles.push(lastParticle);
  45909. }
  45910. };
  45911. ParticleSystem.prototype.getCapacity = function () {
  45912. return this._capacity;
  45913. };
  45914. ParticleSystem.prototype.isAlive = function () {
  45915. return this._alive;
  45916. };
  45917. ParticleSystem.prototype.isStarted = function () {
  45918. return this._started;
  45919. };
  45920. ParticleSystem.prototype.start = function () {
  45921. this._started = true;
  45922. this._stopped = false;
  45923. this._actualFrame = 0;
  45924. };
  45925. ParticleSystem.prototype.stop = function () {
  45926. this._stopped = true;
  45927. };
  45928. // animation sheet
  45929. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  45930. var offset = index * this._vertexBufferSize;
  45931. this._vertexData[offset] = particle.position.x;
  45932. this._vertexData[offset + 1] = particle.position.y;
  45933. this._vertexData[offset + 2] = particle.position.z;
  45934. this._vertexData[offset + 3] = particle.color.r;
  45935. this._vertexData[offset + 4] = particle.color.g;
  45936. this._vertexData[offset + 5] = particle.color.b;
  45937. this._vertexData[offset + 6] = particle.color.a;
  45938. this._vertexData[offset + 7] = particle.angle;
  45939. this._vertexData[offset + 8] = particle.size;
  45940. this._vertexData[offset + 9] = offsetX;
  45941. this._vertexData[offset + 10] = offsetY;
  45942. };
  45943. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  45944. if (offsetX === 0)
  45945. offsetX = this._epsilon;
  45946. else if (offsetX === 1)
  45947. offsetX = 1 - this._epsilon;
  45948. if (offsetY === 0)
  45949. offsetY = this._epsilon;
  45950. else if (offsetY === 1)
  45951. offsetY = 1 - this._epsilon;
  45952. var offset = index * this._vertexBufferSize;
  45953. this._vertexData[offset] = particle.position.x;
  45954. this._vertexData[offset + 1] = particle.position.y;
  45955. this._vertexData[offset + 2] = particle.position.z;
  45956. this._vertexData[offset + 3] = particle.color.r;
  45957. this._vertexData[offset + 4] = particle.color.g;
  45958. this._vertexData[offset + 5] = particle.color.b;
  45959. this._vertexData[offset + 6] = particle.color.a;
  45960. this._vertexData[offset + 7] = particle.angle;
  45961. this._vertexData[offset + 8] = particle.size;
  45962. this._vertexData[offset + 9] = offsetX;
  45963. this._vertexData[offset + 10] = offsetY;
  45964. this._vertexData[offset + 11] = particle.cellIndex;
  45965. };
  45966. ParticleSystem.prototype._update = function (newParticles) {
  45967. // Update current
  45968. this._alive = this.particles.length > 0;
  45969. this.updateFunction(this.particles);
  45970. // Add new ones
  45971. var worldMatrix;
  45972. if (this.emitter.position) {
  45973. var emitterMesh = this.emitter;
  45974. worldMatrix = emitterMesh.getWorldMatrix();
  45975. }
  45976. else {
  45977. var emitterPosition = this.emitter;
  45978. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  45979. }
  45980. var particle;
  45981. for (var index = 0; index < newParticles; index++) {
  45982. if (this.particles.length === this._capacity) {
  45983. break;
  45984. }
  45985. if (this._stockParticles.length !== 0) {
  45986. particle = this._stockParticles.pop();
  45987. particle.age = 0;
  45988. particle.cellIndex = this.startSpriteCellID;
  45989. }
  45990. else {
  45991. particle = new BABYLON.Particle(this);
  45992. }
  45993. this.particles.push(particle);
  45994. var emitPower = ParticleSystem.randomNumber(this.minEmitPower, this.maxEmitPower);
  45995. if (this.startDirectionFunction) {
  45996. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  45997. }
  45998. else {
  45999. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  46000. }
  46001. if (this.startPositionFunction) {
  46002. this.startPositionFunction(worldMatrix, particle.position, particle);
  46003. }
  46004. else {
  46005. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  46006. }
  46007. particle.lifeTime = ParticleSystem.randomNumber(this.minLifeTime, this.maxLifeTime);
  46008. particle.size = ParticleSystem.randomNumber(this.minSize, this.maxSize);
  46009. particle.angularSpeed = ParticleSystem.randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  46010. var step = ParticleSystem.randomNumber(0, 1.0);
  46011. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  46012. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  46013. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  46014. }
  46015. };
  46016. ParticleSystem.prototype._getEffect = function () {
  46017. if (this._customEffect) {
  46018. return this._customEffect;
  46019. }
  46020. ;
  46021. var defines = [];
  46022. if (this._scene.clipPlane) {
  46023. defines.push("#define CLIPPLANE");
  46024. }
  46025. if (this._isAnimationSheetEnabled) {
  46026. defines.push("#define ANIMATESHEET");
  46027. }
  46028. // Effect
  46029. var join = defines.join("\n");
  46030. if (this._cachedDefines !== join) {
  46031. this._cachedDefines = join;
  46032. var attributesNamesOrOptions;
  46033. var effectCreationOption;
  46034. if (this._isAnimationSheetEnabled) {
  46035. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  46036. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  46037. }
  46038. else {
  46039. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  46040. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  46041. }
  46042. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  46043. }
  46044. return this._effect;
  46045. };
  46046. ParticleSystem.prototype.animate = function () {
  46047. if (!this._started)
  46048. return;
  46049. var effect = this._getEffect();
  46050. // Check
  46051. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  46052. return;
  46053. if (this._currentRenderId === this._scene.getRenderId()) {
  46054. return;
  46055. }
  46056. this._currentRenderId = this._scene.getRenderId();
  46057. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  46058. // determine the number of particles we need to create
  46059. var newParticles;
  46060. if (this.manualEmitCount > -1) {
  46061. newParticles = this.manualEmitCount;
  46062. this._newPartsExcess = 0;
  46063. this.manualEmitCount = 0;
  46064. }
  46065. else {
  46066. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  46067. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  46068. }
  46069. if (this._newPartsExcess > 1.0) {
  46070. newParticles += this._newPartsExcess >> 0;
  46071. this._newPartsExcess -= this._newPartsExcess >> 0;
  46072. }
  46073. this._alive = false;
  46074. if (!this._stopped) {
  46075. this._actualFrame += this._scaledUpdateSpeed;
  46076. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  46077. this.stop();
  46078. }
  46079. else {
  46080. newParticles = 0;
  46081. }
  46082. this._update(newParticles);
  46083. // Stopped?
  46084. if (this._stopped) {
  46085. if (!this._alive) {
  46086. this._started = false;
  46087. if (this.onAnimationEnd) {
  46088. this.onAnimationEnd();
  46089. }
  46090. if (this.disposeOnStop) {
  46091. this._scene._toBeDisposed.push(this);
  46092. }
  46093. }
  46094. }
  46095. // Animation sheet
  46096. if (this._isAnimationSheetEnabled) {
  46097. this.appendParticleVertexes = this.appenedParticleVertexesWithSheet;
  46098. }
  46099. else {
  46100. this.appendParticleVertexes = this.appenedParticleVertexesNoSheet;
  46101. }
  46102. // Update VBO
  46103. var offset = 0;
  46104. for (var index = 0; index < this.particles.length; index++) {
  46105. var particle = this.particles[index];
  46106. this.appendParticleVertexes(offset, particle);
  46107. offset += 4;
  46108. }
  46109. if (this._vertexBuffer) {
  46110. this._vertexBuffer.update(this._vertexData);
  46111. }
  46112. };
  46113. ParticleSystem.prototype.appenedParticleVertexesWithSheet = function (offset, particle) {
  46114. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  46115. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  46116. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  46117. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  46118. };
  46119. ParticleSystem.prototype.appenedParticleVertexesNoSheet = function (offset, particle) {
  46120. this._appendParticleVertex(offset++, particle, 0, 0);
  46121. this._appendParticleVertex(offset++, particle, 1, 0);
  46122. this._appendParticleVertex(offset++, particle, 1, 1);
  46123. this._appendParticleVertex(offset++, particle, 0, 1);
  46124. };
  46125. ParticleSystem.prototype.rebuild = function () {
  46126. this._createIndexBuffer();
  46127. if (this._vertexBuffer) {
  46128. this._vertexBuffer._rebuild();
  46129. }
  46130. };
  46131. ParticleSystem.prototype.render = function () {
  46132. var effect = this._getEffect();
  46133. // Check
  46134. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  46135. return 0;
  46136. var engine = this._scene.getEngine();
  46137. // Render
  46138. engine.enableEffect(effect);
  46139. engine.setState(false);
  46140. var viewMatrix = this._scene.getViewMatrix();
  46141. effect.setTexture("diffuseSampler", this.particleTexture);
  46142. effect.setMatrix("view", viewMatrix);
  46143. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  46144. if (this._isAnimationSheetEnabled) {
  46145. var baseSize = this.particleTexture.getBaseSize();
  46146. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  46147. }
  46148. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  46149. if (this._scene.clipPlane) {
  46150. var clipPlane = this._scene.clipPlane;
  46151. var invView = viewMatrix.clone();
  46152. invView.invert();
  46153. effect.setMatrix("invView", invView);
  46154. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  46155. }
  46156. // VBOs
  46157. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  46158. // Draw order
  46159. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  46160. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  46161. }
  46162. else {
  46163. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  46164. }
  46165. if (this.forceDepthWrite) {
  46166. engine.setDepthWrite(true);
  46167. }
  46168. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this.particles.length * 6);
  46169. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  46170. return this.particles.length;
  46171. };
  46172. ParticleSystem.prototype.dispose = function () {
  46173. if (this._vertexBuffer) {
  46174. this._vertexBuffer.dispose();
  46175. this._vertexBuffer = null;
  46176. }
  46177. if (this._indexBuffer) {
  46178. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  46179. this._indexBuffer = null;
  46180. }
  46181. if (this.particleTexture) {
  46182. this.particleTexture.dispose();
  46183. this.particleTexture = null;
  46184. }
  46185. // Remove from scene
  46186. var index = this._scene.particleSystems.indexOf(this);
  46187. if (index > -1) {
  46188. this._scene.particleSystems.splice(index, 1);
  46189. }
  46190. // Callback
  46191. this.onDisposeObservable.notifyObservers(this);
  46192. this.onDisposeObservable.clear();
  46193. };
  46194. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  46195. if (radius === void 0) { radius = 1; }
  46196. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  46197. this.particleEmitterType = particleEmitter;
  46198. return particleEmitter;
  46199. };
  46200. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  46201. if (radius === void 0) { radius = 1; }
  46202. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  46203. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  46204. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  46205. this.particleEmitterType = particleEmitter;
  46206. return particleEmitter;
  46207. };
  46208. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  46209. if (radius === void 0) { radius = 1; }
  46210. if (angle === void 0) { angle = Math.PI / 4; }
  46211. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  46212. this.particleEmitterType = particleEmitter;
  46213. return particleEmitter;
  46214. };
  46215. // 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.
  46216. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  46217. var particleEmitter = new BABYLON.BoxParticleEmitter(this);
  46218. this.direction1 = direction1;
  46219. this.direction2 = direction2;
  46220. this.minEmitBox = minEmitBox;
  46221. this.maxEmitBox = maxEmitBox;
  46222. this.particleEmitterType = particleEmitter;
  46223. return particleEmitter;
  46224. };
  46225. ParticleSystem.randomNumber = function (min, max) {
  46226. if (min === max) {
  46227. return (min);
  46228. }
  46229. var random = Math.random();
  46230. return ((random * (max - min)) + min);
  46231. };
  46232. // Clone
  46233. ParticleSystem.prototype.clone = function (name, newEmitter) {
  46234. var custom = null;
  46235. var program = null;
  46236. if (this.customShader != null) {
  46237. program = this.customShader;
  46238. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  46239. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  46240. }
  46241. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  46242. result.customShader = program;
  46243. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  46244. if (newEmitter === undefined) {
  46245. newEmitter = this.emitter;
  46246. }
  46247. result.emitter = newEmitter;
  46248. if (this.particleTexture) {
  46249. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  46250. }
  46251. if (!this.preventAutoStart) {
  46252. result.start();
  46253. }
  46254. return result;
  46255. };
  46256. ParticleSystem.prototype.serialize = function () {
  46257. var serializationObject = {};
  46258. serializationObject.name = this.name;
  46259. serializationObject.id = this.id;
  46260. // Emitter
  46261. if (this.emitter.position) {
  46262. var emitterMesh = this.emitter;
  46263. serializationObject.emitterId = emitterMesh.id;
  46264. }
  46265. else {
  46266. var emitterPosition = this.emitter;
  46267. serializationObject.emitter = emitterPosition.asArray();
  46268. }
  46269. serializationObject.capacity = this.getCapacity();
  46270. if (this.particleTexture) {
  46271. serializationObject.textureName = this.particleTexture.name;
  46272. }
  46273. // Animations
  46274. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  46275. // Particle system
  46276. serializationObject.minAngularSpeed = this.minAngularSpeed;
  46277. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  46278. serializationObject.minSize = this.minSize;
  46279. serializationObject.maxSize = this.maxSize;
  46280. serializationObject.minEmitPower = this.minEmitPower;
  46281. serializationObject.maxEmitPower = this.maxEmitPower;
  46282. serializationObject.minLifeTime = this.minLifeTime;
  46283. serializationObject.maxLifeTime = this.maxLifeTime;
  46284. serializationObject.emitRate = this.emitRate;
  46285. serializationObject.minEmitBox = this.minEmitBox.asArray();
  46286. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  46287. serializationObject.gravity = this.gravity.asArray();
  46288. serializationObject.direction1 = this.direction1.asArray();
  46289. serializationObject.direction2 = this.direction2.asArray();
  46290. serializationObject.color1 = this.color1.asArray();
  46291. serializationObject.color2 = this.color2.asArray();
  46292. serializationObject.colorDead = this.colorDead.asArray();
  46293. serializationObject.updateSpeed = this.updateSpeed;
  46294. serializationObject.targetStopDuration = this.targetStopDuration;
  46295. serializationObject.textureMask = this.textureMask.asArray();
  46296. serializationObject.blendMode = this.blendMode;
  46297. serializationObject.customShader = this.customShader;
  46298. serializationObject.preventAutoStart = this.preventAutoStart;
  46299. serializationObject.startSpriteCellID = this.startSpriteCellID;
  46300. serializationObject.endSpriteCellID = this.endSpriteCellID;
  46301. serializationObject.spriteCellLoop = this.spriteCellLoop;
  46302. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  46303. serializationObject.spriteCellWidth = this.spriteCellWidth;
  46304. serializationObject.spriteCellHeight = this.spriteCellHeight;
  46305. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  46306. return serializationObject;
  46307. };
  46308. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  46309. var name = parsedParticleSystem.name;
  46310. var custom = null;
  46311. var program = null;
  46312. if (parsedParticleSystem.customShader) {
  46313. program = parsedParticleSystem.customShader;
  46314. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  46315. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  46316. }
  46317. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  46318. particleSystem.customShader = program;
  46319. if (parsedParticleSystem.id) {
  46320. particleSystem.id = parsedParticleSystem.id;
  46321. }
  46322. // Auto start
  46323. if (parsedParticleSystem.preventAutoStart) {
  46324. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  46325. }
  46326. // Texture
  46327. if (parsedParticleSystem.textureName) {
  46328. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  46329. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  46330. }
  46331. // Emitter
  46332. if (parsedParticleSystem.emitterId) {
  46333. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  46334. }
  46335. else {
  46336. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  46337. }
  46338. // Animations
  46339. if (parsedParticleSystem.animations) {
  46340. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  46341. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  46342. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  46343. }
  46344. }
  46345. if (parsedParticleSystem.autoAnimate) {
  46346. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  46347. }
  46348. // Particle system
  46349. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  46350. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  46351. particleSystem.minSize = parsedParticleSystem.minSize;
  46352. particleSystem.maxSize = parsedParticleSystem.maxSize;
  46353. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  46354. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  46355. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  46356. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  46357. particleSystem.emitRate = parsedParticleSystem.emitRate;
  46358. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  46359. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  46360. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  46361. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  46362. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  46363. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  46364. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  46365. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  46366. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  46367. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  46368. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  46369. particleSystem.blendMode = parsedParticleSystem.blendMode;
  46370. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  46371. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  46372. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  46373. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  46374. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  46375. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  46376. if (!particleSystem.preventAutoStart) {
  46377. particleSystem.start();
  46378. }
  46379. return particleSystem;
  46380. };
  46381. // Statics
  46382. ParticleSystem.BLENDMODE_ONEONE = 0;
  46383. ParticleSystem.BLENDMODE_STANDARD = 1;
  46384. return ParticleSystem;
  46385. }());
  46386. BABYLON.ParticleSystem = ParticleSystem;
  46387. })(BABYLON || (BABYLON = {}));
  46388. //# sourceMappingURL=babylon.particleSystem.js.map
  46389. var BABYLON;
  46390. (function (BABYLON) {
  46391. var BoxParticleEmitter = /** @class */ (function () {
  46392. // to be updated like the rest of emitters when breaking changes.
  46393. // all property should be come public variables and passed through constructor.
  46394. function BoxParticleEmitter(_particleSystem) {
  46395. this._particleSystem = _particleSystem;
  46396. }
  46397. Object.defineProperty(BoxParticleEmitter.prototype, "direction1", {
  46398. get: function () {
  46399. return this._particleSystem.direction1;
  46400. },
  46401. set: function (value) {
  46402. this._particleSystem.direction1 = value;
  46403. },
  46404. enumerable: true,
  46405. configurable: true
  46406. });
  46407. Object.defineProperty(BoxParticleEmitter.prototype, "direction2", {
  46408. get: function () {
  46409. return this._particleSystem.direction2;
  46410. },
  46411. set: function (value) {
  46412. this._particleSystem.direction2 = value;
  46413. },
  46414. enumerable: true,
  46415. configurable: true
  46416. });
  46417. Object.defineProperty(BoxParticleEmitter.prototype, "minEmitBox", {
  46418. get: function () {
  46419. return this._particleSystem.minEmitBox;
  46420. },
  46421. set: function (value) {
  46422. this._particleSystem.minEmitBox = value;
  46423. },
  46424. enumerable: true,
  46425. configurable: true
  46426. });
  46427. Object.defineProperty(BoxParticleEmitter.prototype, "maxEmitBox", {
  46428. get: function () {
  46429. return this._particleSystem.maxEmitBox;
  46430. },
  46431. set: function (value) {
  46432. this._particleSystem.maxEmitBox = value;
  46433. },
  46434. enumerable: true,
  46435. configurable: true
  46436. });
  46437. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  46438. var randX = BABYLON.ParticleSystem.randomNumber(this.direction1.x, this.direction2.x);
  46439. var randY = BABYLON.ParticleSystem.randomNumber(this.direction1.y, this.direction2.y);
  46440. var randZ = BABYLON.ParticleSystem.randomNumber(this.direction1.z, this.direction2.z);
  46441. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  46442. };
  46443. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  46444. var randX = BABYLON.ParticleSystem.randomNumber(this.minEmitBox.x, this.maxEmitBox.x);
  46445. var randY = BABYLON.ParticleSystem.randomNumber(this.minEmitBox.y, this.maxEmitBox.y);
  46446. var randZ = BABYLON.ParticleSystem.randomNumber(this.minEmitBox.z, this.maxEmitBox.z);
  46447. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  46448. };
  46449. return BoxParticleEmitter;
  46450. }());
  46451. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  46452. })(BABYLON || (BABYLON = {}));
  46453. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  46454. var BABYLON;
  46455. (function (BABYLON) {
  46456. var ConeParticleEmitter = /** @class */ (function () {
  46457. function ConeParticleEmitter(radius, angle) {
  46458. this.radius = radius;
  46459. this.angle = angle;
  46460. }
  46461. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  46462. if (this.angle === 0) {
  46463. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  46464. }
  46465. else {
  46466. var phi = BABYLON.ParticleSystem.randomNumber(0, 2 * Math.PI);
  46467. var theta = BABYLON.ParticleSystem.randomNumber(0, this.angle);
  46468. var randX = Math.cos(phi) * Math.sin(theta);
  46469. var randY = Math.cos(theta);
  46470. var randZ = Math.sin(phi) * Math.sin(theta);
  46471. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  46472. }
  46473. };
  46474. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  46475. var s = BABYLON.ParticleSystem.randomNumber(0, Math.PI * 2);
  46476. var radius = BABYLON.ParticleSystem.randomNumber(0, this.radius);
  46477. var randX = radius * Math.sin(s);
  46478. var randZ = radius * Math.cos(s);
  46479. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, 0, randZ, worldMatrix, positionToUpdate);
  46480. };
  46481. return ConeParticleEmitter;
  46482. }());
  46483. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  46484. })(BABYLON || (BABYLON = {}));
  46485. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  46486. var BABYLON;
  46487. (function (BABYLON) {
  46488. var SphereParticleEmitter = /** @class */ (function () {
  46489. function SphereParticleEmitter(radius) {
  46490. this.radius = radius;
  46491. }
  46492. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  46493. // measure the direction Vector from the emitter to the particle.
  46494. var direction = particle.position.subtract(worldMatrix.getTranslation());
  46495. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  46496. };
  46497. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  46498. var phi = BABYLON.ParticleSystem.randomNumber(0, 2 * Math.PI);
  46499. var theta = BABYLON.ParticleSystem.randomNumber(0, Math.PI);
  46500. var randX = this.radius * Math.cos(phi) * Math.sin(theta);
  46501. var randY = this.radius * Math.cos(theta);
  46502. var randZ = this.radius * Math.sin(phi) * Math.sin(theta);
  46503. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  46504. };
  46505. return SphereParticleEmitter;
  46506. }());
  46507. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  46508. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  46509. __extends(SphereDirectedParticleEmitter, _super);
  46510. function SphereDirectedParticleEmitter(radius, direction1, direction2) {
  46511. var _this = _super.call(this, radius) || this;
  46512. _this.direction1 = direction1;
  46513. _this.direction2 = direction2;
  46514. return _this;
  46515. }
  46516. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  46517. var randX = BABYLON.ParticleSystem.randomNumber(this.direction1.x, this.direction2.x);
  46518. var randY = BABYLON.ParticleSystem.randomNumber(this.direction1.y, this.direction2.y);
  46519. var randZ = BABYLON.ParticleSystem.randomNumber(this.direction1.z, this.direction2.z);
  46520. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  46521. };
  46522. return SphereDirectedParticleEmitter;
  46523. }(SphereParticleEmitter));
  46524. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  46525. })(BABYLON || (BABYLON = {}));
  46526. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  46527. //# sourceMappingURL=babylon.iParticleEmitterType.js.map
  46528. var BABYLON;
  46529. (function (BABYLON) {
  46530. var GPUParticleSystem = /** @class */ (function () {
  46531. function GPUParticleSystem(name, capacity, scene) {
  46532. this.name = name;
  46533. this.emitter = null;
  46534. this.renderingGroupId = 0;
  46535. this.layerMask = 0x0FFFFFFF; // TODO
  46536. this._updateVertexBuffers = {};
  46537. this._renderVertexBuffers = {};
  46538. this._currentRenderId = -1;
  46539. this._started = true;
  46540. /**
  46541. * An event triggered when the system is disposed.
  46542. * @type {BABYLON.Observable}
  46543. */
  46544. this.onDisposeObservable = new BABYLON.Observable();
  46545. this.id = name;
  46546. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46547. this._capacity = capacity;
  46548. this._engine = this._scene.getEngine();
  46549. this._scene.particleSystems.push(this);
  46550. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "velocity"], [], [], this._scene.getEngine());
  46551. var updateEffectOptions = {
  46552. attributes: ["position", "age", "life", "velocity"],
  46553. uniformsNames: [],
  46554. uniformBuffersNames: [],
  46555. samplers: [],
  46556. defines: "",
  46557. fallbacks: null,
  46558. onCompiled: null,
  46559. onError: null,
  46560. indexParameters: null,
  46561. maxSimultaneousLights: 0,
  46562. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outVelocity"]
  46563. };
  46564. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", updateEffectOptions, this._scene.getEngine());
  46565. }
  46566. GPUParticleSystem.prototype.isStarted = function () {
  46567. return this._started;
  46568. };
  46569. GPUParticleSystem.prototype.start = function () {
  46570. this._started = true;
  46571. };
  46572. GPUParticleSystem.prototype.stop = function () {
  46573. this._started = false;
  46574. };
  46575. GPUParticleSystem.prototype.animate = function () {
  46576. // Do nothing
  46577. };
  46578. GPUParticleSystem.prototype._initialize = function () {
  46579. if (this._renderVAO) {
  46580. return;
  46581. }
  46582. var data = new Array();
  46583. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  46584. // position
  46585. data.push(0.0);
  46586. data.push(0.0);
  46587. data.push(0.0);
  46588. var life = 1 + Math.random() * 10; // TODO: var
  46589. data.push(life + 1); // create the particle as a dead one to create a new one at start
  46590. data.push(life);
  46591. // velocity
  46592. data.push(0.0);
  46593. data.push(0.0);
  46594. data.push(0.0);
  46595. }
  46596. // Update VAO
  46597. this._updateBuffer = new BABYLON.Buffer(this._scene.getEngine(), data, false, 0);
  46598. this._updateVertexBuffers["position"] = this._updateBuffer.createVertexBuffer("position", 0, 3, 3);
  46599. this._updateVertexBuffers["age"] = this._updateBuffer.createVertexBuffer("age", 3, 1, 1);
  46600. this._updateVertexBuffers["life"] = this._updateBuffer.createVertexBuffer("life", 4, 1, 1);
  46601. this._updateVertexBuffers["velocity"] = this._updateBuffer.createVertexBuffer("velocity", 5, 3, 3);
  46602. this._updateVAO = this._engine.recordVertexArrayObject(this._updateVertexBuffers, null, this._updateEffect);
  46603. this._engine.bindArrayBuffer(null);
  46604. // Render VAO
  46605. this._renderBuffer = new BABYLON.Buffer(this._scene.getEngine(), data, false, 0);
  46606. this._renderVertexBuffers["position"] = this._renderBuffer.createVertexBuffer("position", 0, 3, 3);
  46607. this._renderVertexBuffers["age"] = this._renderBuffer.createVertexBuffer("age", 3, 1, 1);
  46608. this._renderVertexBuffers["life"] = this._renderBuffer.createVertexBuffer("life", 4, 1, 1);
  46609. this._renderVertexBuffers["velocity"] = this._renderBuffer.createVertexBuffer("velocity", 5, 3, 3);
  46610. this._renderVAO = this._engine.recordVertexArrayObject(this._renderVertexBuffers, null, this._renderEffect);
  46611. this._engine.bindArrayBuffer(null);
  46612. // Links
  46613. this._sourceVAO = this._updateVAO;
  46614. this._targetVAO = this._renderVAO;
  46615. this._sourceBuffer = this._updateBuffer;
  46616. this._targetBuffer = this._renderBuffer;
  46617. };
  46618. GPUParticleSystem.prototype.render = function () {
  46619. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady()) {
  46620. return 0;
  46621. }
  46622. // Get everything ready to render
  46623. this._initialize();
  46624. if (this._currentRenderId === this._scene.getRenderId()) {
  46625. return 0;
  46626. }
  46627. this._currentRenderId = this._scene.getRenderId();
  46628. // Enable update effect
  46629. this._engine.enableEffect(this._updateEffect);
  46630. this._engine.setState(false);
  46631. // Bind source VAO
  46632. this._engine.bindVertexArrayObject(this._sourceVAO, null);
  46633. // Update
  46634. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  46635. this._engine.setRasterizerState(false);
  46636. this._engine.beginTransformFeedback();
  46637. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._capacity);
  46638. this._engine.endTransformFeedback();
  46639. this._engine.setRasterizerState(true);
  46640. this._engine.bindTransformFeedbackBuffer(null);
  46641. // Enable render effect
  46642. this._engine.enableEffect(this._renderEffect);
  46643. // Bind source VAO
  46644. this._engine.bindVertexArrayObject(this._targetVAO, null);
  46645. // Render
  46646. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._capacity);
  46647. // Switch VAOs
  46648. var tmpVAO = this._sourceVAO;
  46649. this._sourceVAO = this._targetVAO;
  46650. this._targetVAO = tmpVAO;
  46651. // Switch buffers
  46652. var tmpBuffer = this._sourceBuffer;
  46653. this._sourceBuffer = this._targetBuffer;
  46654. this._targetBuffer = tmpBuffer;
  46655. return 0;
  46656. };
  46657. GPUParticleSystem.prototype.rebuild = function () {
  46658. };
  46659. GPUParticleSystem.prototype.dispose = function () {
  46660. var index = this._scene.particleSystems.indexOf(this);
  46661. if (index > -1) {
  46662. this._scene.particleSystems.splice(index, 1);
  46663. }
  46664. //TODO: this._dataBuffer.dispose();
  46665. // Callback
  46666. this.onDisposeObservable.notifyObservers(this);
  46667. this.onDisposeObservable.clear();
  46668. };
  46669. //TODO: Clone / Parse / serialize
  46670. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  46671. return null;
  46672. };
  46673. GPUParticleSystem.prototype.serialize = function () {
  46674. };
  46675. return GPUParticleSystem;
  46676. }());
  46677. BABYLON.GPUParticleSystem = GPUParticleSystem;
  46678. })(BABYLON || (BABYLON = {}));
  46679. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  46680. var BABYLON;
  46681. (function (BABYLON) {
  46682. var SolidParticle = /** @class */ (function () {
  46683. /**
  46684. * Creates a Solid Particle object.
  46685. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  46686. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  46687. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  46688. * `indiceIndex` (integer) is the starting index of the particle indices in the SPS "indices" array.
  46689. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  46690. * `shapeId` (integer) is the model shape identifier in the SPS.
  46691. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  46692. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  46693. */
  46694. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  46695. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  46696. this.idx = 0; // particle global index
  46697. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  46698. this.position = BABYLON.Vector3.Zero(); // position
  46699. this.rotation = BABYLON.Vector3.Zero(); // rotation
  46700. this.scaling = BABYLON.Vector3.One(); // scaling
  46701. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  46702. this.velocity = BABYLON.Vector3.Zero(); // velocity
  46703. this.pivot = BABYLON.Vector3.Zero(); // pivot point in the particle local space
  46704. this.alive = true; // alive
  46705. this.isVisible = true; // visibility
  46706. this._pos = 0; // index of this particle in the global "positions" array
  46707. this._ind = 0; // index of this particle in the global "indices" array
  46708. this.shapeId = 0; // model shape id
  46709. this.idxInShape = 0; // index of the particle in its shape id
  46710. this._stillInvisible = false; // still set as invisible in order to skip useless computations
  46711. this.idx = particleIndex;
  46712. this._pos = positionIndex;
  46713. this._ind = indiceIndex;
  46714. this._model = model;
  46715. this.shapeId = shapeId;
  46716. this.idxInShape = idxInShape;
  46717. this._sps = sps;
  46718. if (modelBoundingInfo) {
  46719. this._modelBoundingInfo = modelBoundingInfo;
  46720. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  46721. }
  46722. }
  46723. Object.defineProperty(SolidParticle.prototype, "scale", {
  46724. /**
  46725. * legacy support, changed scale to scaling
  46726. */
  46727. get: function () {
  46728. return this.scaling;
  46729. },
  46730. set: function (scale) {
  46731. this.scaling = scale;
  46732. },
  46733. enumerable: true,
  46734. configurable: true
  46735. });
  46736. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  46737. /**
  46738. * legacy support, changed quaternion to rotationQuaternion
  46739. */
  46740. get: function () {
  46741. return this.rotationQuaternion;
  46742. },
  46743. set: function (q) {
  46744. this.rotationQuaternion = q;
  46745. },
  46746. enumerable: true,
  46747. configurable: true
  46748. });
  46749. /**
  46750. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  46751. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  46752. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  46753. */
  46754. SolidParticle.prototype.intersectsMesh = function (target) {
  46755. if (!this._boundingInfo || !target._boundingInfo) {
  46756. return false;
  46757. }
  46758. if (this._sps._bSphereOnly) {
  46759. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  46760. }
  46761. return this._boundingInfo.intersects(target._boundingInfo, false);
  46762. };
  46763. return SolidParticle;
  46764. }());
  46765. BABYLON.SolidParticle = SolidParticle;
  46766. var ModelShape = /** @class */ (function () {
  46767. /**
  46768. * 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.
  46769. * SPS internal tool, don't use it manually.
  46770. */
  46771. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  46772. this._indicesLength = 0; // length of the shape in the model indices array
  46773. this.shapeID = id;
  46774. this._shape = shape;
  46775. this._indicesLength = indicesLength;
  46776. this._shapeUV = shapeUV;
  46777. this._positionFunction = posFunction;
  46778. this._vertexFunction = vtxFunction;
  46779. }
  46780. return ModelShape;
  46781. }());
  46782. BABYLON.ModelShape = ModelShape;
  46783. var DepthSortedParticle = /** @class */ (function () {
  46784. function DepthSortedParticle() {
  46785. this.ind = 0; // index of the particle in the "indices" array
  46786. this.indicesLength = 0; // length of the particle shape in the "indices" array
  46787. this.sqDistance = 0.0; // squared distance from the particle to the camera
  46788. }
  46789. return DepthSortedParticle;
  46790. }());
  46791. BABYLON.DepthSortedParticle = DepthSortedParticle;
  46792. })(BABYLON || (BABYLON = {}));
  46793. //# sourceMappingURL=babylon.solidParticle.js.map
  46794. var BABYLON;
  46795. (function (BABYLON) {
  46796. /**
  46797. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  46798. */
  46799. var SolidParticleSystem = /** @class */ (function () {
  46800. /**
  46801. * Creates a SPS (Solid Particle System) object.
  46802. * `name` (String) is the SPS name, this will be the underlying mesh name.
  46803. * `scene` (Scene) is the scene in which the SPS is added.
  46804. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  46805. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  46806. * `enableDepthSort` (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  46807. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  46808. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  46809. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  46810. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  46811. */
  46812. function SolidParticleSystem(name, scene, options) {
  46813. // public members
  46814. /**
  46815. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  46816. * Example : var p = SPS.particles[i];
  46817. */
  46818. this.particles = new Array();
  46819. /**
  46820. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  46821. */
  46822. this.nbParticles = 0;
  46823. /**
  46824. * If the particles must ever face the camera (default false). Useful for planar particles.
  46825. */
  46826. this.billboard = false;
  46827. /**
  46828. * Recompute normals when adding a shape
  46829. */
  46830. this.recomputeNormals = true;
  46831. /**
  46832. * This a counter ofr your own usage. It's not set by any SPS functions.
  46833. */
  46834. this.counter = 0;
  46835. /**
  46836. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  46837. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  46838. */
  46839. this.vars = {};
  46840. this._positions = new Array();
  46841. this._indices = new Array();
  46842. this._normals = new Array();
  46843. this._colors = new Array();
  46844. this._uvs = new Array();
  46845. this._index = 0; // indices index
  46846. this._updatable = true;
  46847. this._pickable = false;
  46848. this._isVisibilityBoxLocked = false;
  46849. this._alwaysVisible = false;
  46850. this._depthSort = false;
  46851. this._shapeCounter = 0;
  46852. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  46853. this._color = new BABYLON.Color4(0, 0, 0, 0);
  46854. this._computeParticleColor = true;
  46855. this._computeParticleTexture = true;
  46856. this._computeParticleRotation = true;
  46857. this._computeParticleVertex = false;
  46858. this._computeBoundingBox = false;
  46859. this._depthSortParticles = true;
  46860. this._cam_axisZ = BABYLON.Vector3.Zero();
  46861. this._cam_axisY = BABYLON.Vector3.Zero();
  46862. this._cam_axisX = BABYLON.Vector3.Zero();
  46863. this._axisZ = BABYLON.Axis.Z;
  46864. this._camDir = BABYLON.Vector3.Zero();
  46865. this._camInvertedPosition = BABYLON.Vector3.Zero();
  46866. this._rotMatrix = new BABYLON.Matrix();
  46867. this._invertMatrix = new BABYLON.Matrix();
  46868. this._rotated = BABYLON.Vector3.Zero();
  46869. this._quaternion = new BABYLON.Quaternion();
  46870. this._vertex = BABYLON.Vector3.Zero();
  46871. this._normal = BABYLON.Vector3.Zero();
  46872. this._yaw = 0.0;
  46873. this._pitch = 0.0;
  46874. this._roll = 0.0;
  46875. this._halfroll = 0.0;
  46876. this._halfpitch = 0.0;
  46877. this._halfyaw = 0.0;
  46878. this._sinRoll = 0.0;
  46879. this._cosRoll = 0.0;
  46880. this._sinPitch = 0.0;
  46881. this._cosPitch = 0.0;
  46882. this._sinYaw = 0.0;
  46883. this._cosYaw = 0.0;
  46884. this._mustUnrotateFixedNormals = false;
  46885. this._minimum = BABYLON.Tmp.Vector3[0];
  46886. this._maximum = BABYLON.Tmp.Vector3[1];
  46887. this._minBbox = BABYLON.Tmp.Vector3[4];
  46888. this._maxBbox = BABYLON.Tmp.Vector3[5];
  46889. this._particlesIntersect = false;
  46890. this._depthSortFunction = function (p1, p2) {
  46891. return (p2.sqDistance - p1.sqDistance);
  46892. };
  46893. this._needs32Bits = false;
  46894. this._bSphereOnly = false;
  46895. this._bSphereRadiusFactor = 1.0;
  46896. this.name = name;
  46897. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46898. this._camera = scene.activeCamera;
  46899. this._pickable = options ? options.isPickable : false;
  46900. this._depthSort = options ? options.enableDepthSort : false;
  46901. this._particlesIntersect = options ? options.particleIntersection : false;
  46902. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  46903. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  46904. if (options && options.updatable) {
  46905. this._updatable = options.updatable;
  46906. }
  46907. else {
  46908. this._updatable = true;
  46909. }
  46910. if (this._pickable) {
  46911. this.pickedParticles = [];
  46912. }
  46913. if (this._depthSort) {
  46914. this.depthSortedParticles = [];
  46915. }
  46916. }
  46917. /**
  46918. * Builds the SPS underlying mesh. Returns a standard Mesh.
  46919. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  46920. */
  46921. SolidParticleSystem.prototype.buildMesh = function () {
  46922. if (this.nbParticles === 0) {
  46923. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  46924. this.addShape(triangle, 1);
  46925. triangle.dispose();
  46926. }
  46927. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  46928. this._positions32 = new Float32Array(this._positions);
  46929. this._uvs32 = new Float32Array(this._uvs);
  46930. this._colors32 = new Float32Array(this._colors);
  46931. if (this.recomputeNormals) {
  46932. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  46933. }
  46934. this._normals32 = new Float32Array(this._normals);
  46935. this._fixedNormal32 = new Float32Array(this._normals);
  46936. if (this._mustUnrotateFixedNormals) {
  46937. this._unrotateFixedNormals();
  46938. }
  46939. var vertexData = new BABYLON.VertexData();
  46940. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  46941. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  46942. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  46943. if (this._uvs32) {
  46944. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  46945. ;
  46946. }
  46947. if (this._colors32) {
  46948. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  46949. }
  46950. var mesh = new BABYLON.Mesh(this.name, this._scene);
  46951. vertexData.applyToMesh(mesh, this._updatable);
  46952. this.mesh = mesh;
  46953. this.mesh.isPickable = this._pickable;
  46954. // free memory
  46955. if (!this._depthSort) {
  46956. this._indices = null;
  46957. }
  46958. this._positions = null;
  46959. this._normals = null;
  46960. this._uvs = null;
  46961. this._colors = null;
  46962. if (!this._updatable) {
  46963. this.particles.length = 0;
  46964. }
  46965. return mesh;
  46966. };
  46967. /**
  46968. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  46969. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  46970. * Thus the particles generated from `digest()` have their property `position` set yet.
  46971. * `mesh` ( Mesh ) is the mesh to be digested
  46972. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  46973. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  46974. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  46975. */
  46976. SolidParticleSystem.prototype.digest = function (mesh, options) {
  46977. var size = (options && options.facetNb) || 1;
  46978. var number = (options && options.number) || 0;
  46979. var delta = (options && options.delta) || 0;
  46980. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  46981. var meshInd = mesh.getIndices();
  46982. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  46983. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  46984. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  46985. var f = 0; // facet counter
  46986. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  46987. // compute size from number
  46988. if (number) {
  46989. number = (number > totalFacets) ? totalFacets : number;
  46990. size = Math.round(totalFacets / number);
  46991. delta = 0;
  46992. }
  46993. else {
  46994. size = (size > totalFacets) ? totalFacets : size;
  46995. }
  46996. var facetPos = []; // submesh positions
  46997. var facetInd = []; // submesh indices
  46998. var facetUV = []; // submesh UV
  46999. var facetCol = []; // submesh colors
  47000. var barycenter = BABYLON.Tmp.Vector3[0];
  47001. var sizeO = size;
  47002. while (f < totalFacets) {
  47003. size = sizeO + Math.floor((1 + delta) * Math.random());
  47004. if (f > totalFacets - size) {
  47005. size = totalFacets - f;
  47006. }
  47007. // reset temp arrays
  47008. facetPos.length = 0;
  47009. facetInd.length = 0;
  47010. facetUV.length = 0;
  47011. facetCol.length = 0;
  47012. // iterate over "size" facets
  47013. var fi = 0;
  47014. for (var j = f * 3; j < (f + size) * 3; j++) {
  47015. facetInd.push(fi);
  47016. var i = meshInd[j];
  47017. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  47018. if (meshUV) {
  47019. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  47020. }
  47021. if (meshCol) {
  47022. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  47023. }
  47024. fi++;
  47025. }
  47026. // create a model shape for each single particle
  47027. var idx = this.nbParticles;
  47028. var shape = this._posToShape(facetPos);
  47029. var shapeUV = this._uvsToShapeUV(facetUV);
  47030. // compute the barycenter of the shape
  47031. var v;
  47032. for (v = 0; v < shape.length; v++) {
  47033. barycenter.addInPlace(shape[v]);
  47034. }
  47035. barycenter.scaleInPlace(1 / shape.length);
  47036. // shift the shape from its barycenter to the origin
  47037. for (v = 0; v < shape.length; v++) {
  47038. shape[v].subtractInPlace(barycenter);
  47039. }
  47040. var bInfo;
  47041. if (this._particlesIntersect) {
  47042. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  47043. }
  47044. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  47045. // add the particle in the SPS
  47046. var currentPos = this._positions.length;
  47047. var currentInd = this._indices.length;
  47048. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  47049. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  47050. // initialize the particle position
  47051. this.particles[this.nbParticles].position.addInPlace(barycenter);
  47052. this._index += shape.length;
  47053. idx++;
  47054. this.nbParticles++;
  47055. this._shapeCounter++;
  47056. f += size;
  47057. }
  47058. return this;
  47059. };
  47060. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  47061. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  47062. var index = 0;
  47063. var idx = 0;
  47064. for (var p = 0; p < this.particles.length; p++) {
  47065. this._particle = this.particles[p];
  47066. this._shape = this._particle._model._shape;
  47067. if (this._particle.rotationQuaternion) {
  47068. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  47069. }
  47070. else {
  47071. this._yaw = this._particle.rotation.y;
  47072. this._pitch = this._particle.rotation.x;
  47073. this._roll = this._particle.rotation.z;
  47074. this._quaternionRotationYPR();
  47075. }
  47076. this._quaternionToRotationMatrix();
  47077. this._rotMatrix.invertToRef(this._invertMatrix);
  47078. for (var pt = 0; pt < this._shape.length; pt++) {
  47079. idx = index + pt * 3;
  47080. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  47081. this._fixedNormal32[idx] = this._normal.x;
  47082. this._fixedNormal32[idx + 1] = this._normal.y;
  47083. this._fixedNormal32[idx + 2] = this._normal.z;
  47084. }
  47085. index = idx + 3;
  47086. }
  47087. };
  47088. //reset copy
  47089. SolidParticleSystem.prototype._resetCopy = function () {
  47090. this._copy.position.x = 0;
  47091. this._copy.position.y = 0;
  47092. this._copy.position.z = 0;
  47093. this._copy.rotation.x = 0;
  47094. this._copy.rotation.y = 0;
  47095. this._copy.rotation.z = 0;
  47096. this._copy.rotationQuaternion = null;
  47097. this._copy.scaling.x = 1.0;
  47098. this._copy.scaling.y = 1.0;
  47099. this._copy.scaling.z = 1.0;
  47100. this._copy.uvs.x = 0;
  47101. this._copy.uvs.y = 0;
  47102. this._copy.uvs.z = 1.0;
  47103. this._copy.uvs.w = 1.0;
  47104. this._copy.color = null;
  47105. };
  47106. // _meshBuilder : inserts the shape model in the global SPS mesh
  47107. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  47108. var i;
  47109. var u = 0;
  47110. var c = 0;
  47111. var n = 0;
  47112. this._resetCopy();
  47113. if (options && options.positionFunction) {
  47114. options.positionFunction(this._copy, idx, idxInShape);
  47115. this._mustUnrotateFixedNormals = true;
  47116. }
  47117. if (this._copy.rotationQuaternion) {
  47118. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  47119. }
  47120. else {
  47121. this._yaw = this._copy.rotation.y;
  47122. this._pitch = this._copy.rotation.x;
  47123. this._roll = this._copy.rotation.z;
  47124. this._quaternionRotationYPR();
  47125. }
  47126. this._quaternionToRotationMatrix();
  47127. for (i = 0; i < shape.length; i++) {
  47128. this._vertex.x = shape[i].x;
  47129. this._vertex.y = shape[i].y;
  47130. this._vertex.z = shape[i].z;
  47131. if (options && options.vertexFunction) {
  47132. options.vertexFunction(this._copy, this._vertex, i);
  47133. }
  47134. this._vertex.x *= this._copy.scaling.x;
  47135. this._vertex.y *= this._copy.scaling.y;
  47136. this._vertex.z *= this._copy.scaling.z;
  47137. this._vertex.x += this._copy.pivot.x;
  47138. this._vertex.y += this._copy.pivot.y;
  47139. this._vertex.z += this._copy.pivot.z;
  47140. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  47141. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  47142. if (meshUV) {
  47143. 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);
  47144. u += 2;
  47145. }
  47146. if (this._copy.color) {
  47147. this._color = this._copy.color;
  47148. }
  47149. else if (meshCol && meshCol[c] !== undefined) {
  47150. this._color.r = meshCol[c];
  47151. this._color.g = meshCol[c + 1];
  47152. this._color.b = meshCol[c + 2];
  47153. this._color.a = meshCol[c + 3];
  47154. }
  47155. else {
  47156. this._color.r = 1.0;
  47157. this._color.g = 1.0;
  47158. this._color.b = 1.0;
  47159. this._color.a = 1.0;
  47160. }
  47161. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  47162. c += 4;
  47163. if (!this.recomputeNormals && meshNor) {
  47164. this._normal.x = meshNor[n];
  47165. this._normal.y = meshNor[n + 1];
  47166. this._normal.z = meshNor[n + 2];
  47167. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  47168. normals.push(this._normal.x, this._normal.y, this._normal.z);
  47169. n += 3;
  47170. }
  47171. }
  47172. for (i = 0; i < meshInd.length; i++) {
  47173. var current_ind = p + meshInd[i];
  47174. indices.push(current_ind);
  47175. if (current_ind > 65535) {
  47176. this._needs32Bits = true;
  47177. }
  47178. }
  47179. if (this._pickable) {
  47180. var nbfaces = meshInd.length / 3;
  47181. for (i = 0; i < nbfaces; i++) {
  47182. this.pickedParticles.push({ idx: idx, faceId: i });
  47183. }
  47184. }
  47185. if (this._depthSort) {
  47186. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  47187. }
  47188. return this._copy;
  47189. };
  47190. // returns a shape array from positions array
  47191. SolidParticleSystem.prototype._posToShape = function (positions) {
  47192. var shape = [];
  47193. for (var i = 0; i < positions.length; i += 3) {
  47194. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  47195. }
  47196. return shape;
  47197. };
  47198. // returns a shapeUV array from a Vector4 uvs
  47199. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  47200. var shapeUV = [];
  47201. if (uvs) {
  47202. for (var i = 0; i < uvs.length; i++)
  47203. shapeUV.push(uvs[i]);
  47204. }
  47205. return shapeUV;
  47206. };
  47207. // adds a new particle object in the particles array
  47208. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  47209. if (bInfo === void 0) { bInfo = null; }
  47210. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  47211. this.particles.push(sp);
  47212. return sp;
  47213. };
  47214. /**
  47215. * Adds some particles to the SPS from the model shape. Returns the shape id.
  47216. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  47217. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  47218. * `nb` (positive integer) the number of particles to be created from this model
  47219. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  47220. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  47221. */
  47222. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  47223. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47224. var meshInd = mesh.getIndices();
  47225. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47226. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  47227. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47228. var bbInfo;
  47229. if (this._particlesIntersect) {
  47230. bbInfo = mesh.getBoundingInfo();
  47231. }
  47232. var shape = this._posToShape(meshPos);
  47233. var shapeUV = this._uvsToShapeUV(meshUV);
  47234. var posfunc = options ? options.positionFunction : null;
  47235. var vtxfunc = options ? options.vertexFunction : null;
  47236. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  47237. // particles
  47238. var sp;
  47239. var currentCopy;
  47240. var idx = this.nbParticles;
  47241. for (var i = 0; i < nb; i++) {
  47242. var currentPos = this._positions.length;
  47243. var currentInd = this._indices.length;
  47244. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  47245. if (this._updatable) {
  47246. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  47247. sp.position.copyFrom(currentCopy.position);
  47248. sp.rotation.copyFrom(currentCopy.rotation);
  47249. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  47250. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  47251. }
  47252. if (currentCopy.color && sp.color) {
  47253. sp.color.copyFrom(currentCopy.color);
  47254. }
  47255. sp.scaling.copyFrom(currentCopy.scaling);
  47256. sp.uvs.copyFrom(currentCopy.uvs);
  47257. }
  47258. this._index += shape.length;
  47259. idx++;
  47260. }
  47261. this.nbParticles += nb;
  47262. this._shapeCounter++;
  47263. return this._shapeCounter - 1;
  47264. };
  47265. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  47266. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  47267. this._resetCopy();
  47268. if (particle._model._positionFunction) {
  47269. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  47270. }
  47271. if (this._copy.rotationQuaternion) {
  47272. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  47273. }
  47274. else {
  47275. this._yaw = this._copy.rotation.y;
  47276. this._pitch = this._copy.rotation.x;
  47277. this._roll = this._copy.rotation.z;
  47278. this._quaternionRotationYPR();
  47279. }
  47280. this._quaternionToRotationMatrix();
  47281. this._shape = particle._model._shape;
  47282. for (var pt = 0; pt < this._shape.length; pt++) {
  47283. this._vertex.x = this._shape[pt].x;
  47284. this._vertex.y = this._shape[pt].y;
  47285. this._vertex.z = this._shape[pt].z;
  47286. if (particle._model._vertexFunction) {
  47287. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  47288. }
  47289. this._vertex.x *= this._copy.scaling.x;
  47290. this._vertex.y *= this._copy.scaling.y;
  47291. this._vertex.z *= this._copy.scaling.z;
  47292. this._vertex.x += this._copy.pivot.x;
  47293. this._vertex.y += this._copy.pivot.y;
  47294. this._vertex.z += this._copy.pivot.z;
  47295. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  47296. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  47297. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  47298. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  47299. }
  47300. particle.position.x = 0.0;
  47301. particle.position.y = 0.0;
  47302. particle.position.z = 0.0;
  47303. particle.rotation.x = 0.0;
  47304. particle.rotation.y = 0.0;
  47305. particle.rotation.z = 0.0;
  47306. particle.rotationQuaternion = null;
  47307. particle.scaling.x = 1.0;
  47308. particle.scaling.y = 1.0;
  47309. particle.scaling.z = 1.0;
  47310. };
  47311. /**
  47312. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  47313. * Returns the SPS.
  47314. */
  47315. SolidParticleSystem.prototype.rebuildMesh = function () {
  47316. for (var p = 0; p < this.particles.length; p++) {
  47317. this._rebuildParticle(this.particles[p]);
  47318. }
  47319. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  47320. return this;
  47321. };
  47322. /**
  47323. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  47324. * This method calls `updateParticle()` for each particle of the SPS.
  47325. * For an animated SPS, it is usually called within the render loop.
  47326. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  47327. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  47328. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  47329. * Returns the SPS.
  47330. */
  47331. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  47332. if (start === void 0) { start = 0; }
  47333. if (end === void 0) { end = this.nbParticles - 1; }
  47334. if (update === void 0) { update = true; }
  47335. if (!this._updatable) {
  47336. return this;
  47337. }
  47338. // custom beforeUpdate
  47339. this.beforeUpdateParticles(start, end, update);
  47340. this._cam_axisX.x = 1.0;
  47341. this._cam_axisX.y = 0.0;
  47342. this._cam_axisX.z = 0.0;
  47343. this._cam_axisY.x = 0.0;
  47344. this._cam_axisY.y = 1.0;
  47345. this._cam_axisY.z = 0.0;
  47346. this._cam_axisZ.x = 0.0;
  47347. this._cam_axisZ.y = 0.0;
  47348. this._cam_axisZ.z = 1.0;
  47349. // cases when the World Matrix is to be computed first
  47350. if (this.billboard || this._depthSort) {
  47351. this.mesh.computeWorldMatrix(true);
  47352. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  47353. }
  47354. // if the particles will always face the camera
  47355. if (this.billboard) {
  47356. // compute the camera position and un-rotate it by the current mesh rotation
  47357. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  47358. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  47359. this._cam_axisZ.normalize();
  47360. // same for camera up vector extracted from the cam view matrix
  47361. var view = this._camera.getViewMatrix(true);
  47362. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  47363. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  47364. this._cam_axisY.normalize();
  47365. this._cam_axisX.normalize();
  47366. }
  47367. // if depthSort, compute the camera global position in the mesh local system
  47368. if (this._depthSort) {
  47369. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  47370. }
  47371. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  47372. var idx = 0; // current position index in the global array positions32
  47373. var index = 0; // position start index in the global array positions32 of the current particle
  47374. var colidx = 0; // current color index in the global array colors32
  47375. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  47376. var uvidx = 0; // current uv index in the global array uvs32
  47377. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  47378. var pt = 0; // current index in the particle model shape
  47379. if (this.mesh.isFacetDataEnabled) {
  47380. this._computeBoundingBox = true;
  47381. }
  47382. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  47383. if (this._computeBoundingBox) {
  47384. if (start == 0 && end == this.nbParticles - 1) {
  47385. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  47386. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  47387. }
  47388. else {
  47389. if (this.mesh._boundingInfo) {
  47390. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  47391. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  47392. }
  47393. }
  47394. }
  47395. // particle loop
  47396. index = this.particles[start]._pos;
  47397. var vpos = (index / 3) | 0;
  47398. colorIndex = vpos * 4;
  47399. uvIndex = vpos * 2;
  47400. for (var p = start; p <= end; p++) {
  47401. this._particle = this.particles[p];
  47402. this._shape = this._particle._model._shape;
  47403. this._shapeUV = this._particle._model._shapeUV;
  47404. // call to custom user function to update the particle properties
  47405. this.updateParticle(this._particle);
  47406. // camera-particle distance for depth sorting
  47407. if (this._depthSort && this._depthSortParticles) {
  47408. var dsp = this.depthSortedParticles[p];
  47409. dsp.ind = this._particle._ind;
  47410. dsp.indicesLength = this._particle._model._indicesLength;
  47411. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  47412. }
  47413. // skip the computations for inactive or already invisible particles
  47414. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  47415. // increment indexes for the next particle
  47416. pt = this._shape.length;
  47417. index += pt * 3;
  47418. colorIndex += pt * 4;
  47419. uvIndex += pt * 2;
  47420. continue;
  47421. }
  47422. if (this._particle.isVisible) {
  47423. this._particle._stillInvisible = false; // un-mark permanent invisibility
  47424. // particle rotation matrix
  47425. if (this.billboard) {
  47426. this._particle.rotation.x = 0.0;
  47427. this._particle.rotation.y = 0.0;
  47428. }
  47429. if (this._computeParticleRotation || this.billboard) {
  47430. if (this._particle.rotationQuaternion) {
  47431. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  47432. }
  47433. else {
  47434. this._yaw = this._particle.rotation.y;
  47435. this._pitch = this._particle.rotation.x;
  47436. this._roll = this._particle.rotation.z;
  47437. this._quaternionRotationYPR();
  47438. }
  47439. this._quaternionToRotationMatrix();
  47440. }
  47441. // particle vertex loop
  47442. for (pt = 0; pt < this._shape.length; pt++) {
  47443. idx = index + pt * 3;
  47444. colidx = colorIndex + pt * 4;
  47445. uvidx = uvIndex + pt * 2;
  47446. this._vertex.x = this._shape[pt].x;
  47447. this._vertex.y = this._shape[pt].y;
  47448. this._vertex.z = this._shape[pt].z;
  47449. if (this._computeParticleVertex) {
  47450. this.updateParticleVertex(this._particle, this._vertex, pt);
  47451. }
  47452. // positions
  47453. this._vertex.x *= this._particle.scaling.x;
  47454. this._vertex.y *= this._particle.scaling.y;
  47455. this._vertex.z *= this._particle.scaling.z;
  47456. this._vertex.x += this._particle.pivot.x;
  47457. this._vertex.y += this._particle.pivot.y;
  47458. this._vertex.z += this._particle.pivot.z;
  47459. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  47460. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  47461. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  47462. this._positions32[idx] = 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;
  47463. this._positions32[idx + 1] = 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;
  47464. this._positions32[idx + 2] = 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;
  47465. if (this._computeBoundingBox) {
  47466. if (this._positions32[idx] < this._minimum.x) {
  47467. this._minimum.x = this._positions32[idx];
  47468. }
  47469. if (this._positions32[idx] > this._maximum.x) {
  47470. this._maximum.x = this._positions32[idx];
  47471. }
  47472. if (this._positions32[idx + 1] < this._minimum.y) {
  47473. this._minimum.y = this._positions32[idx + 1];
  47474. }
  47475. if (this._positions32[idx + 1] > this._maximum.y) {
  47476. this._maximum.y = this._positions32[idx + 1];
  47477. }
  47478. if (this._positions32[idx + 2] < this._minimum.z) {
  47479. this._minimum.z = this._positions32[idx + 2];
  47480. }
  47481. if (this._positions32[idx + 2] > this._maximum.z) {
  47482. this._maximum.z = this._positions32[idx + 2];
  47483. }
  47484. }
  47485. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  47486. if (!this._computeParticleVertex) {
  47487. this._normal.x = this._fixedNormal32[idx];
  47488. this._normal.y = this._fixedNormal32[idx + 1];
  47489. this._normal.z = this._fixedNormal32[idx + 2];
  47490. this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8];
  47491. this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9];
  47492. this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10];
  47493. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  47494. 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;
  47495. 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;
  47496. }
  47497. if (this._computeParticleColor && this._particle.color) {
  47498. this._colors32[colidx] = this._particle.color.r;
  47499. this._colors32[colidx + 1] = this._particle.color.g;
  47500. this._colors32[colidx + 2] = this._particle.color.b;
  47501. this._colors32[colidx + 3] = this._particle.color.a;
  47502. }
  47503. if (this._computeParticleTexture) {
  47504. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  47505. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  47506. }
  47507. }
  47508. }
  47509. else {
  47510. this._particle._stillInvisible = true; // mark the particle as invisible
  47511. for (pt = 0; pt < this._shape.length; pt++) {
  47512. idx = index + pt * 3;
  47513. colidx = colorIndex + pt * 4;
  47514. uvidx = uvIndex + pt * 2;
  47515. this._positions32[idx] = 0.0;
  47516. this._positions32[idx + 1] = 0.0;
  47517. this._positions32[idx + 2] = 0.0;
  47518. this._normals32[idx] = 0.0;
  47519. this._normals32[idx + 1] = 0.0;
  47520. this._normals32[idx + 2] = 0.0;
  47521. if (this._computeParticleColor && this._particle.color) {
  47522. this._colors32[colidx] = this._particle.color.r;
  47523. this._colors32[colidx + 1] = this._particle.color.g;
  47524. this._colors32[colidx + 2] = this._particle.color.b;
  47525. this._colors32[colidx + 3] = this._particle.color.a;
  47526. }
  47527. if (this._computeParticleTexture) {
  47528. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  47529. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  47530. }
  47531. }
  47532. }
  47533. // if the particle intersections must be computed : update the bbInfo
  47534. if (this._particlesIntersect) {
  47535. var bInfo = this._particle._boundingInfo;
  47536. var bBox = bInfo.boundingBox;
  47537. var bSphere = bInfo.boundingSphere;
  47538. if (!this._bSphereOnly) {
  47539. // place, scale and rotate the particle bbox within the SPS local system, then update it
  47540. for (var b = 0; b < bBox.vectors.length; b++) {
  47541. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  47542. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  47543. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  47544. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  47545. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  47546. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  47547. 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;
  47548. 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;
  47549. 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;
  47550. }
  47551. bBox._update(this.mesh._worldMatrix);
  47552. }
  47553. // place and scale the particle bouding sphere in the SPS local system, then update it
  47554. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  47555. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  47556. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  47557. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  47558. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  47559. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  47560. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  47561. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  47562. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  47563. 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));
  47564. bSphere._update(this.mesh._worldMatrix);
  47565. }
  47566. // increment indexes for the next particle
  47567. index = idx + 3;
  47568. colorIndex = colidx + 4;
  47569. uvIndex = uvidx + 2;
  47570. }
  47571. // if the VBO must be updated
  47572. if (update) {
  47573. if (this._computeParticleColor) {
  47574. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  47575. }
  47576. if (this._computeParticleTexture) {
  47577. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  47578. }
  47579. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  47580. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  47581. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  47582. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  47583. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  47584. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  47585. for (var i = 0; i < this._normals32.length; i++) {
  47586. this._fixedNormal32[i] = this._normals32[i];
  47587. }
  47588. }
  47589. if (!this.mesh.areNormalsFrozen) {
  47590. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  47591. }
  47592. }
  47593. if (this._depthSort && this._depthSortParticles) {
  47594. this.depthSortedParticles.sort(this._depthSortFunction);
  47595. var dspl = this.depthSortedParticles.length;
  47596. var sorted = 0;
  47597. var lind = 0;
  47598. var sind = 0;
  47599. var sid = 0;
  47600. for (sorted = 0; sorted < dspl; sorted++) {
  47601. lind = this.depthSortedParticles[sorted].indicesLength;
  47602. sind = this.depthSortedParticles[sorted].ind;
  47603. for (var i = 0; i < lind; i++) {
  47604. this._indices32[sid] = this._indices[sind + i];
  47605. sid++;
  47606. }
  47607. }
  47608. this.mesh.updateIndices(this._indices32);
  47609. }
  47610. }
  47611. if (this._computeBoundingBox) {
  47612. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  47613. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  47614. }
  47615. this.afterUpdateParticles(start, end, update);
  47616. return this;
  47617. };
  47618. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  47619. this._halfroll = this._roll * 0.5;
  47620. this._halfpitch = this._pitch * 0.5;
  47621. this._halfyaw = this._yaw * 0.5;
  47622. this._sinRoll = Math.sin(this._halfroll);
  47623. this._cosRoll = Math.cos(this._halfroll);
  47624. this._sinPitch = Math.sin(this._halfpitch);
  47625. this._cosPitch = Math.cos(this._halfpitch);
  47626. this._sinYaw = Math.sin(this._halfyaw);
  47627. this._cosYaw = Math.cos(this._halfyaw);
  47628. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  47629. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  47630. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  47631. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  47632. };
  47633. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  47634. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  47635. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  47636. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  47637. this._rotMatrix.m[3] = 0;
  47638. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  47639. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  47640. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  47641. this._rotMatrix.m[7] = 0;
  47642. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  47643. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  47644. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  47645. this._rotMatrix.m[11] = 0;
  47646. this._rotMatrix.m[12] = 0;
  47647. this._rotMatrix.m[13] = 0;
  47648. this._rotMatrix.m[14] = 0;
  47649. this._rotMatrix.m[15] = 1.0;
  47650. };
  47651. /**
  47652. * Disposes the SPS.
  47653. * Returns nothing.
  47654. */
  47655. SolidParticleSystem.prototype.dispose = function () {
  47656. this.mesh.dispose();
  47657. this.vars = null;
  47658. // drop references to internal big arrays for the GC
  47659. this._positions = null;
  47660. this._indices = null;
  47661. this._normals = null;
  47662. this._uvs = null;
  47663. this._colors = null;
  47664. this._indices32 = null;
  47665. this._positions32 = null;
  47666. this._normals32 = null;
  47667. this._fixedNormal32 = null;
  47668. this._uvs32 = null;
  47669. this._colors32 = null;
  47670. this.pickedParticles = null;
  47671. };
  47672. /**
  47673. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  47674. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  47675. * Returns the SPS.
  47676. */
  47677. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  47678. if (!this._isVisibilityBoxLocked) {
  47679. this.mesh.refreshBoundingInfo();
  47680. }
  47681. return this;
  47682. };
  47683. /**
  47684. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  47685. * @param size the size (float) of the visibility box
  47686. * note : this doesn't lock the SPS mesh bounding box.
  47687. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  47688. */
  47689. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  47690. var vis = size / 2;
  47691. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  47692. };
  47693. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  47694. // getter and setter
  47695. get: function () {
  47696. return this._alwaysVisible;
  47697. },
  47698. /**
  47699. * Sets the SPS as always visible or not
  47700. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  47701. */
  47702. set: function (val) {
  47703. this._alwaysVisible = val;
  47704. this.mesh.alwaysSelectAsActiveMesh = val;
  47705. },
  47706. enumerable: true,
  47707. configurable: true
  47708. });
  47709. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  47710. get: function () {
  47711. return this._isVisibilityBoxLocked;
  47712. },
  47713. /**
  47714. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  47715. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  47716. */
  47717. set: function (val) {
  47718. this._isVisibilityBoxLocked = val;
  47719. var boundingInfo = this.mesh.getBoundingInfo();
  47720. boundingInfo.isLocked = val;
  47721. },
  47722. enumerable: true,
  47723. configurable: true
  47724. });
  47725. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  47726. // getters
  47727. get: function () {
  47728. return this._computeParticleRotation;
  47729. },
  47730. // Optimizer setters
  47731. /**
  47732. * Tells to `setParticles()` to compute the particle rotations or not.
  47733. * Default value : true. The SPS is faster when it's set to false.
  47734. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  47735. */
  47736. set: function (val) {
  47737. this._computeParticleRotation = val;
  47738. },
  47739. enumerable: true,
  47740. configurable: true
  47741. });
  47742. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  47743. get: function () {
  47744. return this._computeParticleColor;
  47745. },
  47746. /**
  47747. * Tells to `setParticles()` to compute the particle colors or not.
  47748. * Default value : true. The SPS is faster when it's set to false.
  47749. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  47750. */
  47751. set: function (val) {
  47752. this._computeParticleColor = val;
  47753. },
  47754. enumerable: true,
  47755. configurable: true
  47756. });
  47757. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  47758. get: function () {
  47759. return this._computeParticleTexture;
  47760. },
  47761. /**
  47762. * Tells to `setParticles()` to compute the particle textures or not.
  47763. * Default value : true. The SPS is faster when it's set to false.
  47764. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  47765. */
  47766. set: function (val) {
  47767. this._computeParticleTexture = val;
  47768. },
  47769. enumerable: true,
  47770. configurable: true
  47771. });
  47772. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  47773. get: function () {
  47774. return this._computeParticleVertex;
  47775. },
  47776. /**
  47777. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  47778. * Default value : false. The SPS is faster when it's set to false.
  47779. * Note : the particle custom vertex positions aren't stored values.
  47780. */
  47781. set: function (val) {
  47782. this._computeParticleVertex = val;
  47783. },
  47784. enumerable: true,
  47785. configurable: true
  47786. });
  47787. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  47788. get: function () {
  47789. return this._computeBoundingBox;
  47790. },
  47791. /**
  47792. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  47793. */
  47794. set: function (val) {
  47795. this._computeBoundingBox = val;
  47796. },
  47797. enumerable: true,
  47798. configurable: true
  47799. });
  47800. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  47801. get: function () {
  47802. return this._depthSortParticles;
  47803. },
  47804. /**
  47805. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  47806. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  47807. * Default : `true`
  47808. */
  47809. set: function (val) {
  47810. this._depthSortParticles = val;
  47811. },
  47812. enumerable: true,
  47813. configurable: true
  47814. });
  47815. // =======================================================================
  47816. // Particle behavior logic
  47817. // these following methods may be overwritten by the user to fit his needs
  47818. /**
  47819. * This function does nothing. It may be overwritten to set all the particle first values.
  47820. * The SPS doesn't call this function, you may have to call it by your own.
  47821. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  47822. */
  47823. SolidParticleSystem.prototype.initParticles = function () {
  47824. };
  47825. /**
  47826. * This function does nothing. It may be overwritten to recycle a particle.
  47827. * The SPS doesn't call this function, you may have to call it by your own.
  47828. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  47829. */
  47830. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  47831. return particle;
  47832. };
  47833. /**
  47834. * Updates a particle : this function should be overwritten by the user.
  47835. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  47836. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  47837. * ex : just set a particle position or velocity and recycle conditions
  47838. */
  47839. SolidParticleSystem.prototype.updateParticle = function (particle) {
  47840. return particle;
  47841. };
  47842. /**
  47843. * Updates a vertex of a particle : it can be overwritten by the user.
  47844. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  47845. * @param particle the current particle
  47846. * @param vertex the current index of the current particle
  47847. * @param pt the index of the current vertex in the particle shape
  47848. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  47849. * ex : just set a vertex particle position
  47850. */
  47851. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  47852. return vertex;
  47853. };
  47854. /**
  47855. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  47856. * This does nothing and may be overwritten by the user.
  47857. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  47858. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  47859. * @param update the boolean update value actually passed to setParticles()
  47860. */
  47861. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  47862. };
  47863. /**
  47864. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  47865. * This will be passed three parameters.
  47866. * This does nothing and may be overwritten by the user.
  47867. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  47868. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  47869. * @param update the boolean update value actually passed to setParticles()
  47870. */
  47871. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  47872. };
  47873. return SolidParticleSystem;
  47874. }());
  47875. BABYLON.SolidParticleSystem = SolidParticleSystem;
  47876. })(BABYLON || (BABYLON = {}));
  47877. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  47878. var BABYLON;
  47879. (function (BABYLON) {
  47880. var GroundMesh = /** @class */ (function (_super) {
  47881. __extends(GroundMesh, _super);
  47882. function GroundMesh(name, scene) {
  47883. var _this = _super.call(this, name, scene) || this;
  47884. _this.generateOctree = false;
  47885. return _this;
  47886. }
  47887. GroundMesh.prototype.getClassName = function () {
  47888. return "GroundMesh";
  47889. };
  47890. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  47891. get: function () {
  47892. return Math.min(this._subdivisionsX, this._subdivisionsY);
  47893. },
  47894. enumerable: true,
  47895. configurable: true
  47896. });
  47897. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  47898. get: function () {
  47899. return this._subdivisionsX;
  47900. },
  47901. enumerable: true,
  47902. configurable: true
  47903. });
  47904. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  47905. get: function () {
  47906. return this._subdivisionsY;
  47907. },
  47908. enumerable: true,
  47909. configurable: true
  47910. });
  47911. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  47912. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  47913. this._subdivisionsX = chunksCount;
  47914. this._subdivisionsY = chunksCount;
  47915. this.subdivide(chunksCount);
  47916. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  47917. };
  47918. /**
  47919. * Returns a height (y) value in the Worl system :
  47920. * the ground altitude at the coordinates (x, z) expressed in the World system.
  47921. * Returns the ground y position if (x, z) are outside the ground surface.
  47922. */
  47923. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  47924. var world = this.getWorldMatrix();
  47925. var invMat = BABYLON.Tmp.Matrix[5];
  47926. world.invertToRef(invMat);
  47927. var tmpVect = BABYLON.Tmp.Vector3[8];
  47928. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  47929. x = tmpVect.x;
  47930. z = tmpVect.z;
  47931. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  47932. return this.position.y;
  47933. }
  47934. if (!this._heightQuads || this._heightQuads.length == 0) {
  47935. this._initHeightQuads();
  47936. this._computeHeightQuads();
  47937. }
  47938. var facet = this._getFacetAt(x, z);
  47939. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  47940. // return y in the World system
  47941. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  47942. return tmpVect.y;
  47943. };
  47944. /**
  47945. * Returns a normalized vector (Vector3) orthogonal to the ground
  47946. * at the ground coordinates (x, z) expressed in the World system.
  47947. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  47948. */
  47949. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  47950. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  47951. this.getNormalAtCoordinatesToRef(x, z, normal);
  47952. return normal;
  47953. };
  47954. /**
  47955. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  47956. * at the ground coordinates (x, z) expressed in the World system.
  47957. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  47958. * Returns the GroundMesh.
  47959. */
  47960. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  47961. var world = this.getWorldMatrix();
  47962. var tmpMat = BABYLON.Tmp.Matrix[5];
  47963. world.invertToRef(tmpMat);
  47964. var tmpVect = BABYLON.Tmp.Vector3[8];
  47965. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  47966. x = tmpVect.x;
  47967. z = tmpVect.z;
  47968. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  47969. return this;
  47970. }
  47971. if (!this._heightQuads || this._heightQuads.length == 0) {
  47972. this._initHeightQuads();
  47973. this._computeHeightQuads();
  47974. }
  47975. var facet = this._getFacetAt(x, z);
  47976. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  47977. return this;
  47978. };
  47979. /**
  47980. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  47981. * if the ground has been updated.
  47982. * This can be used in the render loop.
  47983. * Returns the GroundMesh.
  47984. */
  47985. GroundMesh.prototype.updateCoordinateHeights = function () {
  47986. if (!this._heightQuads || this._heightQuads.length == 0) {
  47987. this._initHeightQuads();
  47988. }
  47989. this._computeHeightQuads();
  47990. return this;
  47991. };
  47992. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  47993. GroundMesh.prototype._getFacetAt = function (x, z) {
  47994. // retrieve col and row from x, z coordinates in the ground local system
  47995. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  47996. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  47997. var quad = this._heightQuads[row * this._subdivisionsX + col];
  47998. var facet;
  47999. if (z < quad.slope.x * x + quad.slope.y) {
  48000. facet = quad.facet1;
  48001. }
  48002. else {
  48003. facet = quad.facet2;
  48004. }
  48005. return facet;
  48006. };
  48007. // Creates and populates the heightMap array with "facet" elements :
  48008. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  48009. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  48010. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  48011. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  48012. // Returns the GroundMesh.
  48013. GroundMesh.prototype._initHeightQuads = function () {
  48014. var subdivisionsX = this._subdivisionsX;
  48015. var subdivisionsY = this._subdivisionsY;
  48016. this._heightQuads = new Array();
  48017. for (var row = 0; row < subdivisionsY; row++) {
  48018. for (var col = 0; col < subdivisionsX; col++) {
  48019. 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) };
  48020. this._heightQuads[row * subdivisionsX + col] = quad;
  48021. }
  48022. }
  48023. return this;
  48024. };
  48025. // Compute each quad element values and update the the heightMap array :
  48026. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  48027. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  48028. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  48029. // Returns the GroundMesh.
  48030. GroundMesh.prototype._computeHeightQuads = function () {
  48031. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48032. if (!positions) {
  48033. return this;
  48034. }
  48035. var v1 = BABYLON.Tmp.Vector3[3];
  48036. var v2 = BABYLON.Tmp.Vector3[2];
  48037. var v3 = BABYLON.Tmp.Vector3[1];
  48038. var v4 = BABYLON.Tmp.Vector3[0];
  48039. var v1v2 = BABYLON.Tmp.Vector3[4];
  48040. var v1v3 = BABYLON.Tmp.Vector3[5];
  48041. var v1v4 = BABYLON.Tmp.Vector3[6];
  48042. var norm1 = BABYLON.Tmp.Vector3[7];
  48043. var norm2 = BABYLON.Tmp.Vector3[8];
  48044. var i = 0;
  48045. var j = 0;
  48046. var k = 0;
  48047. var cd = 0; // 2D slope coefficient : z = cd * x + h
  48048. var h = 0;
  48049. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  48050. var d2 = 0;
  48051. var subdivisionsX = this._subdivisionsX;
  48052. var subdivisionsY = this._subdivisionsY;
  48053. for (var row = 0; row < subdivisionsY; row++) {
  48054. for (var col = 0; col < subdivisionsX; col++) {
  48055. i = col * 3;
  48056. j = row * (subdivisionsX + 1) * 3;
  48057. k = (row + 1) * (subdivisionsX + 1) * 3;
  48058. v1.x = positions[j + i];
  48059. v1.y = positions[j + i + 1];
  48060. v1.z = positions[j + i + 2];
  48061. v2.x = positions[j + i + 3];
  48062. v2.y = positions[j + i + 4];
  48063. v2.z = positions[j + i + 5];
  48064. v3.x = positions[k + i];
  48065. v3.y = positions[k + i + 1];
  48066. v3.z = positions[k + i + 2];
  48067. v4.x = positions[k + i + 3];
  48068. v4.y = positions[k + i + 4];
  48069. v4.z = positions[k + i + 5];
  48070. // 2D slope V1V4
  48071. cd = (v4.z - v1.z) / (v4.x - v1.x);
  48072. h = v1.z - cd * v1.x; // v1 belongs to the slope
  48073. // facet equations :
  48074. // we compute each facet normal vector
  48075. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  48076. // we compute the value d by applying the equation to v1 which belongs to the plane
  48077. // then we store the facet equation in a Vector4
  48078. v2.subtractToRef(v1, v1v2);
  48079. v3.subtractToRef(v1, v1v3);
  48080. v4.subtractToRef(v1, v1v4);
  48081. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  48082. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  48083. norm1.normalize();
  48084. norm2.normalize();
  48085. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  48086. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  48087. var quad = this._heightQuads[row * subdivisionsX + col];
  48088. quad.slope.copyFromFloats(cd, h);
  48089. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  48090. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  48091. }
  48092. }
  48093. return this;
  48094. };
  48095. GroundMesh.prototype.serialize = function (serializationObject) {
  48096. _super.prototype.serialize.call(this, serializationObject);
  48097. serializationObject.subdivisionsX = this._subdivisionsX;
  48098. serializationObject.subdivisionsY = this._subdivisionsY;
  48099. serializationObject.minX = this._minX;
  48100. serializationObject.maxX = this._maxX;
  48101. serializationObject.minZ = this._minZ;
  48102. serializationObject.maxZ = this._maxZ;
  48103. serializationObject.width = this._width;
  48104. serializationObject.height = this._height;
  48105. };
  48106. GroundMesh.Parse = function (parsedMesh, scene) {
  48107. var result = new GroundMesh(parsedMesh.name, scene);
  48108. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  48109. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  48110. result._minX = parsedMesh.minX;
  48111. result._maxX = parsedMesh.maxX;
  48112. result._minZ = parsedMesh.minZ;
  48113. result._maxZ = parsedMesh.maxZ;
  48114. result._width = parsedMesh.width;
  48115. result._height = parsedMesh.height;
  48116. return result;
  48117. };
  48118. return GroundMesh;
  48119. }(BABYLON.Mesh));
  48120. BABYLON.GroundMesh = GroundMesh;
  48121. })(BABYLON || (BABYLON = {}));
  48122. //# sourceMappingURL=babylon.groundMesh.js.map
  48123. var BABYLON;
  48124. (function (BABYLON) {
  48125. /**
  48126. * Creates an instance based on a source mesh.
  48127. */
  48128. var InstancedMesh = /** @class */ (function (_super) {
  48129. __extends(InstancedMesh, _super);
  48130. function InstancedMesh(name, source) {
  48131. var _this = _super.call(this, name, source.getScene()) || this;
  48132. source.instances.push(_this);
  48133. _this._sourceMesh = source;
  48134. _this.position.copyFrom(source.position);
  48135. _this.rotation.copyFrom(source.rotation);
  48136. _this.scaling.copyFrom(source.scaling);
  48137. if (source.rotationQuaternion) {
  48138. _this.rotationQuaternion = source.rotationQuaternion.clone();
  48139. }
  48140. _this.infiniteDistance = source.infiniteDistance;
  48141. _this.setPivotMatrix(source.getPivotMatrix());
  48142. _this.refreshBoundingInfo();
  48143. _this._syncSubMeshes();
  48144. return _this;
  48145. }
  48146. /**
  48147. * Returns the string "InstancedMesh".
  48148. */
  48149. InstancedMesh.prototype.getClassName = function () {
  48150. return "InstancedMesh";
  48151. };
  48152. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  48153. // Methods
  48154. get: function () {
  48155. return this._sourceMesh.receiveShadows;
  48156. },
  48157. enumerable: true,
  48158. configurable: true
  48159. });
  48160. Object.defineProperty(InstancedMesh.prototype, "material", {
  48161. get: function () {
  48162. return this._sourceMesh.material;
  48163. },
  48164. enumerable: true,
  48165. configurable: true
  48166. });
  48167. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  48168. get: function () {
  48169. return this._sourceMesh.visibility;
  48170. },
  48171. enumerable: true,
  48172. configurable: true
  48173. });
  48174. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  48175. get: function () {
  48176. return this._sourceMesh.skeleton;
  48177. },
  48178. enumerable: true,
  48179. configurable: true
  48180. });
  48181. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  48182. get: function () {
  48183. return this._sourceMesh.renderingGroupId;
  48184. },
  48185. enumerable: true,
  48186. configurable: true
  48187. });
  48188. /**
  48189. * Returns the total number of vertices (integer).
  48190. */
  48191. InstancedMesh.prototype.getTotalVertices = function () {
  48192. return this._sourceMesh.getTotalVertices();
  48193. };
  48194. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  48195. get: function () {
  48196. return this._sourceMesh;
  48197. },
  48198. enumerable: true,
  48199. configurable: true
  48200. });
  48201. /**
  48202. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  48203. */
  48204. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  48205. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  48206. };
  48207. /**
  48208. * Sets the vertex data of the mesh geometry for the requested `kind`.
  48209. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  48210. * The `data` are either a numeric array either a Float32Array.
  48211. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  48212. * 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).
  48213. * Note that a new underlying VertexBuffer object is created each call.
  48214. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  48215. *
  48216. * Possible `kind` values :
  48217. * - BABYLON.VertexBuffer.PositionKind
  48218. * - BABYLON.VertexBuffer.UVKind
  48219. * - BABYLON.VertexBuffer.UV2Kind
  48220. * - BABYLON.VertexBuffer.UV3Kind
  48221. * - BABYLON.VertexBuffer.UV4Kind
  48222. * - BABYLON.VertexBuffer.UV5Kind
  48223. * - BABYLON.VertexBuffer.UV6Kind
  48224. * - BABYLON.VertexBuffer.ColorKind
  48225. * - BABYLON.VertexBuffer.MatricesIndicesKind
  48226. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  48227. * - BABYLON.VertexBuffer.MatricesWeightsKind
  48228. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  48229. *
  48230. * Returns the Mesh.
  48231. */
  48232. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  48233. if (this.sourceMesh) {
  48234. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  48235. }
  48236. return this.sourceMesh;
  48237. };
  48238. /**
  48239. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  48240. * If the mesh has no geometry, it is simply returned as it is.
  48241. * The `data` are either a numeric array either a Float32Array.
  48242. * No new underlying VertexBuffer object is created.
  48243. * 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.
  48244. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  48245. *
  48246. * Possible `kind` values :
  48247. * - BABYLON.VertexBuffer.PositionKind
  48248. * - BABYLON.VertexBuffer.UVKind
  48249. * - BABYLON.VertexBuffer.UV2Kind
  48250. * - BABYLON.VertexBuffer.UV3Kind
  48251. * - BABYLON.VertexBuffer.UV4Kind
  48252. * - BABYLON.VertexBuffer.UV5Kind
  48253. * - BABYLON.VertexBuffer.UV6Kind
  48254. * - BABYLON.VertexBuffer.ColorKind
  48255. * - BABYLON.VertexBuffer.MatricesIndicesKind
  48256. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  48257. * - BABYLON.VertexBuffer.MatricesWeightsKind
  48258. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  48259. *
  48260. * Returns the Mesh.
  48261. */
  48262. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  48263. if (this.sourceMesh) {
  48264. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  48265. }
  48266. return this.sourceMesh;
  48267. };
  48268. /**
  48269. * Sets the mesh indices.
  48270. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  48271. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  48272. * This method creates a new index buffer each call.
  48273. * Returns the Mesh.
  48274. */
  48275. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  48276. if (totalVertices === void 0) { totalVertices = null; }
  48277. if (this.sourceMesh) {
  48278. this.sourceMesh.setIndices(indices, totalVertices);
  48279. }
  48280. return this.sourceMesh;
  48281. };
  48282. /**
  48283. * Boolean : True if the mesh owns the requested kind of data.
  48284. */
  48285. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  48286. return this._sourceMesh.isVerticesDataPresent(kind);
  48287. };
  48288. /**
  48289. * Returns an array of indices (IndicesArray).
  48290. */
  48291. InstancedMesh.prototype.getIndices = function () {
  48292. return this._sourceMesh.getIndices();
  48293. };
  48294. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  48295. get: function () {
  48296. return this._sourceMesh._positions;
  48297. },
  48298. enumerable: true,
  48299. configurable: true
  48300. });
  48301. /**
  48302. * Sets a new updated BoundingInfo to the mesh.
  48303. * Returns the mesh.
  48304. */
  48305. InstancedMesh.prototype.refreshBoundingInfo = function () {
  48306. var meshBB = this._sourceMesh.getBoundingInfo();
  48307. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  48308. this._updateBoundingInfo();
  48309. return this;
  48310. };
  48311. InstancedMesh.prototype._preActivate = function () {
  48312. if (this._currentLOD) {
  48313. this._currentLOD._preActivate();
  48314. }
  48315. return this;
  48316. };
  48317. InstancedMesh.prototype._activate = function (renderId) {
  48318. if (this._currentLOD) {
  48319. this._currentLOD._registerInstanceForRenderId(this, renderId);
  48320. }
  48321. return this;
  48322. };
  48323. /**
  48324. * Returns the current associated LOD AbstractMesh.
  48325. */
  48326. InstancedMesh.prototype.getLOD = function (camera) {
  48327. if (!camera) {
  48328. return this;
  48329. }
  48330. var boundingInfo = this.getBoundingInfo();
  48331. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  48332. if (this._currentLOD === this.sourceMesh) {
  48333. return this;
  48334. }
  48335. return this._currentLOD;
  48336. };
  48337. InstancedMesh.prototype._syncSubMeshes = function () {
  48338. this.releaseSubMeshes();
  48339. if (this._sourceMesh.subMeshes) {
  48340. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  48341. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  48342. }
  48343. }
  48344. return this;
  48345. };
  48346. InstancedMesh.prototype._generatePointsArray = function () {
  48347. return this._sourceMesh._generatePointsArray();
  48348. };
  48349. /**
  48350. * Creates a new InstancedMesh from the current mesh.
  48351. * - name (string) : the cloned mesh name
  48352. * - newParent (optional Node) : the optional Node to parent the clone to.
  48353. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  48354. *
  48355. * Returns the clone.
  48356. */
  48357. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  48358. var result = this._sourceMesh.createInstance(name);
  48359. // Deep copy
  48360. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  48361. // Bounding info
  48362. this.refreshBoundingInfo();
  48363. // Parent
  48364. if (newParent) {
  48365. result.parent = newParent;
  48366. }
  48367. if (!doNotCloneChildren) {
  48368. // Children
  48369. for (var index = 0; index < this.getScene().meshes.length; index++) {
  48370. var mesh = this.getScene().meshes[index];
  48371. if (mesh.parent === this) {
  48372. mesh.clone(mesh.name, result);
  48373. }
  48374. }
  48375. }
  48376. result.computeWorldMatrix(true);
  48377. return result;
  48378. };
  48379. /**
  48380. * Disposes the InstancedMesh.
  48381. * Returns nothing.
  48382. */
  48383. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  48384. // Remove from mesh
  48385. var index = this._sourceMesh.instances.indexOf(this);
  48386. this._sourceMesh.instances.splice(index, 1);
  48387. _super.prototype.dispose.call(this, doNotRecurse);
  48388. };
  48389. return InstancedMesh;
  48390. }(BABYLON.AbstractMesh));
  48391. BABYLON.InstancedMesh = InstancedMesh;
  48392. })(BABYLON || (BABYLON = {}));
  48393. //# sourceMappingURL=babylon.instancedMesh.js.map
  48394. var BABYLON;
  48395. (function (BABYLON) {
  48396. var LinesMesh = /** @class */ (function (_super) {
  48397. __extends(LinesMesh, _super);
  48398. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  48399. if (scene === void 0) { scene = null; }
  48400. if (parent === void 0) { parent = null; }
  48401. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  48402. _this.useVertexColor = useVertexColor;
  48403. _this.useVertexAlpha = useVertexAlpha;
  48404. _this.color = new BABYLON.Color3(1, 1, 1);
  48405. _this.alpha = 1;
  48406. if (source) {
  48407. _this.color = source.color.clone();
  48408. _this.alpha = source.alpha;
  48409. _this.useVertexColor = source.useVertexColor;
  48410. _this.useVertexAlpha = source.useVertexAlpha;
  48411. }
  48412. _this._intersectionThreshold = 0.1;
  48413. var defines = [];
  48414. var options = {
  48415. attributes: [BABYLON.VertexBuffer.PositionKind],
  48416. uniforms: ["world", "viewProjection"],
  48417. needAlphaBlending: true,
  48418. defines: defines
  48419. };
  48420. if (useVertexAlpha === false) {
  48421. options.needAlphaBlending = false;
  48422. }
  48423. if (!useVertexColor) {
  48424. options.uniforms.push("color");
  48425. }
  48426. else {
  48427. options.defines.push("#define VERTEXCOLOR");
  48428. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  48429. }
  48430. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  48431. return _this;
  48432. }
  48433. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  48434. /**
  48435. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  48436. * This margin is expressed in world space coordinates, so its value may vary.
  48437. * Default value is 0.1
  48438. * @returns the intersection Threshold value.
  48439. */
  48440. get: function () {
  48441. return this._intersectionThreshold;
  48442. },
  48443. /**
  48444. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  48445. * This margin is expressed in world space coordinates, so its value may vary.
  48446. * @param value the new threshold to apply
  48447. */
  48448. set: function (value) {
  48449. if (this._intersectionThreshold === value) {
  48450. return;
  48451. }
  48452. this._intersectionThreshold = value;
  48453. if (this.geometry) {
  48454. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  48455. }
  48456. },
  48457. enumerable: true,
  48458. configurable: true
  48459. });
  48460. /**
  48461. * Returns the string "LineMesh"
  48462. */
  48463. LinesMesh.prototype.getClassName = function () {
  48464. return "LinesMesh";
  48465. };
  48466. Object.defineProperty(LinesMesh.prototype, "material", {
  48467. get: function () {
  48468. return this._colorShader;
  48469. },
  48470. set: function (value) {
  48471. // Do nothing
  48472. },
  48473. enumerable: true,
  48474. configurable: true
  48475. });
  48476. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  48477. get: function () {
  48478. return false;
  48479. },
  48480. enumerable: true,
  48481. configurable: true
  48482. });
  48483. LinesMesh.prototype.createInstance = function (name) {
  48484. throw new Error("LinesMeshes do not support createInstance.");
  48485. };
  48486. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  48487. if (!this._geometry) {
  48488. return this;
  48489. }
  48490. // VBOs
  48491. this._geometry._bind(this._colorShader.getEffect());
  48492. // Color
  48493. if (!this.useVertexColor) {
  48494. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  48495. }
  48496. return this;
  48497. };
  48498. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  48499. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  48500. return this;
  48501. }
  48502. var engine = this.getScene().getEngine();
  48503. // Draw order
  48504. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  48505. return this;
  48506. };
  48507. LinesMesh.prototype.dispose = function (doNotRecurse) {
  48508. this._colorShader.dispose();
  48509. _super.prototype.dispose.call(this, doNotRecurse);
  48510. };
  48511. /**
  48512. * Returns a new LineMesh object cloned from the current one.
  48513. */
  48514. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  48515. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  48516. };
  48517. return LinesMesh;
  48518. }(BABYLON.Mesh));
  48519. BABYLON.LinesMesh = LinesMesh;
  48520. })(BABYLON || (BABYLON = {}));
  48521. //# sourceMappingURL=babylon.linesMesh.js.map
  48522. var BABYLON;
  48523. (function (BABYLON) {
  48524. var ShaderMaterial = /** @class */ (function (_super) {
  48525. __extends(ShaderMaterial, _super);
  48526. function ShaderMaterial(name, scene, shaderPath, options) {
  48527. var _this = _super.call(this, name, scene) || this;
  48528. _this._textures = {};
  48529. _this._textureArrays = {};
  48530. _this._floats = {};
  48531. _this._ints = {};
  48532. _this._floatsArrays = {};
  48533. _this._colors3 = {};
  48534. _this._colors3Arrays = {};
  48535. _this._colors4 = {};
  48536. _this._vectors2 = {};
  48537. _this._vectors3 = {};
  48538. _this._vectors4 = {};
  48539. _this._matrices = {};
  48540. _this._matrices3x3 = {};
  48541. _this._matrices2x2 = {};
  48542. _this._vectors2Arrays = {};
  48543. _this._vectors3Arrays = {};
  48544. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  48545. _this._shaderPath = shaderPath;
  48546. options.needAlphaBlending = options.needAlphaBlending || false;
  48547. options.needAlphaTesting = options.needAlphaTesting || false;
  48548. options.attributes = options.attributes || ["position", "normal", "uv"];
  48549. options.uniforms = options.uniforms || ["worldViewProjection"];
  48550. options.uniformBuffers = options.uniformBuffers || [];
  48551. options.samplers = options.samplers || [];
  48552. options.defines = options.defines || [];
  48553. _this._options = options;
  48554. return _this;
  48555. }
  48556. ShaderMaterial.prototype.getClassName = function () {
  48557. return "ShaderMaterial";
  48558. };
  48559. ShaderMaterial.prototype.needAlphaBlending = function () {
  48560. return this._options.needAlphaBlending;
  48561. };
  48562. ShaderMaterial.prototype.needAlphaTesting = function () {
  48563. return this._options.needAlphaTesting;
  48564. };
  48565. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  48566. if (this._options.uniforms.indexOf(uniformName) === -1) {
  48567. this._options.uniforms.push(uniformName);
  48568. }
  48569. };
  48570. ShaderMaterial.prototype.setTexture = function (name, texture) {
  48571. if (this._options.samplers.indexOf(name) === -1) {
  48572. this._options.samplers.push(name);
  48573. }
  48574. this._textures[name] = texture;
  48575. return this;
  48576. };
  48577. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  48578. if (this._options.samplers.indexOf(name) === -1) {
  48579. this._options.samplers.push(name);
  48580. }
  48581. this._checkUniform(name);
  48582. this._textureArrays[name] = textures;
  48583. return this;
  48584. };
  48585. ShaderMaterial.prototype.setFloat = function (name, value) {
  48586. this._checkUniform(name);
  48587. this._floats[name] = value;
  48588. return this;
  48589. };
  48590. ShaderMaterial.prototype.setInt = function (name, value) {
  48591. this._checkUniform(name);
  48592. this._ints[name] = value;
  48593. return this;
  48594. };
  48595. ShaderMaterial.prototype.setFloats = function (name, value) {
  48596. this._checkUniform(name);
  48597. this._floatsArrays[name] = value;
  48598. return this;
  48599. };
  48600. ShaderMaterial.prototype.setColor3 = function (name, value) {
  48601. this._checkUniform(name);
  48602. this._colors3[name] = value;
  48603. return this;
  48604. };
  48605. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  48606. this._checkUniform(name);
  48607. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  48608. color.toArray(arr, arr.length);
  48609. return arr;
  48610. }, []);
  48611. return this;
  48612. };
  48613. ShaderMaterial.prototype.setColor4 = function (name, value) {
  48614. this._checkUniform(name);
  48615. this._colors4[name] = value;
  48616. return this;
  48617. };
  48618. ShaderMaterial.prototype.setVector2 = function (name, value) {
  48619. this._checkUniform(name);
  48620. this._vectors2[name] = value;
  48621. return this;
  48622. };
  48623. ShaderMaterial.prototype.setVector3 = function (name, value) {
  48624. this._checkUniform(name);
  48625. this._vectors3[name] = value;
  48626. return this;
  48627. };
  48628. ShaderMaterial.prototype.setVector4 = function (name, value) {
  48629. this._checkUniform(name);
  48630. this._vectors4[name] = value;
  48631. return this;
  48632. };
  48633. ShaderMaterial.prototype.setMatrix = function (name, value) {
  48634. this._checkUniform(name);
  48635. this._matrices[name] = value;
  48636. return this;
  48637. };
  48638. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  48639. this._checkUniform(name);
  48640. this._matrices3x3[name] = value;
  48641. return this;
  48642. };
  48643. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  48644. this._checkUniform(name);
  48645. this._matrices2x2[name] = value;
  48646. return this;
  48647. };
  48648. ShaderMaterial.prototype.setArray2 = function (name, value) {
  48649. this._checkUniform(name);
  48650. this._vectors2Arrays[name] = value;
  48651. return this;
  48652. };
  48653. ShaderMaterial.prototype.setArray3 = function (name, value) {
  48654. this._checkUniform(name);
  48655. this._vectors3Arrays[name] = value;
  48656. return this;
  48657. };
  48658. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  48659. if (!mesh) {
  48660. return true;
  48661. }
  48662. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  48663. return false;
  48664. }
  48665. return false;
  48666. };
  48667. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  48668. var scene = this.getScene();
  48669. var engine = scene.getEngine();
  48670. if (!this.checkReadyOnEveryCall) {
  48671. if (this._renderId === scene.getRenderId()) {
  48672. if (this._checkCache(scene, mesh, useInstances)) {
  48673. return true;
  48674. }
  48675. }
  48676. }
  48677. // Instances
  48678. var defines = [];
  48679. var attribs = [];
  48680. var fallbacks = new BABYLON.EffectFallbacks();
  48681. if (useInstances) {
  48682. defines.push("#define INSTANCES");
  48683. }
  48684. for (var index = 0; index < this._options.defines.length; index++) {
  48685. defines.push(this._options.defines[index]);
  48686. }
  48687. for (var index = 0; index < this._options.attributes.length; index++) {
  48688. attribs.push(this._options.attributes[index]);
  48689. }
  48690. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  48691. attribs.push(BABYLON.VertexBuffer.ColorKind);
  48692. defines.push("#define VERTEXCOLOR");
  48693. }
  48694. // Bones
  48695. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  48696. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  48697. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  48698. if (mesh.numBoneInfluencers > 4) {
  48699. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  48700. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  48701. }
  48702. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  48703. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  48704. fallbacks.addCPUSkinningFallback(0, mesh);
  48705. if (this._options.uniforms.indexOf("mBones") === -1) {
  48706. this._options.uniforms.push("mBones");
  48707. }
  48708. }
  48709. else {
  48710. defines.push("#define NUM_BONE_INFLUENCERS 0");
  48711. }
  48712. // Textures
  48713. for (var name in this._textures) {
  48714. if (!this._textures[name].isReady()) {
  48715. return false;
  48716. }
  48717. }
  48718. // Alpha test
  48719. if (engine.getAlphaTesting()) {
  48720. defines.push("#define ALPHATEST");
  48721. }
  48722. var previousEffect = this._effect;
  48723. var join = defines.join("\n");
  48724. this._effect = engine.createEffect(this._shaderPath, {
  48725. attributes: attribs,
  48726. uniformsNames: this._options.uniforms,
  48727. uniformBuffersNames: this._options.uniformBuffers,
  48728. samplers: this._options.samplers,
  48729. defines: join,
  48730. fallbacks: fallbacks,
  48731. onCompiled: this.onCompiled,
  48732. onError: this.onError
  48733. }, engine);
  48734. if (!this._effect.isReady()) {
  48735. return false;
  48736. }
  48737. if (previousEffect !== this._effect) {
  48738. scene.resetCachedMaterial();
  48739. }
  48740. this._renderId = scene.getRenderId();
  48741. return true;
  48742. };
  48743. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  48744. var scene = this.getScene();
  48745. if (!this._effect) {
  48746. return;
  48747. }
  48748. if (this._options.uniforms.indexOf("world") !== -1) {
  48749. this._effect.setMatrix("world", world);
  48750. }
  48751. if (this._options.uniforms.indexOf("worldView") !== -1) {
  48752. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  48753. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  48754. }
  48755. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  48756. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  48757. }
  48758. };
  48759. ShaderMaterial.prototype.bind = function (world, mesh) {
  48760. // Std values
  48761. this.bindOnlyWorldMatrix(world);
  48762. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  48763. if (this._options.uniforms.indexOf("view") !== -1) {
  48764. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  48765. }
  48766. if (this._options.uniforms.indexOf("projection") !== -1) {
  48767. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  48768. }
  48769. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  48770. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  48771. }
  48772. // Bones
  48773. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  48774. var name;
  48775. // Texture
  48776. for (name in this._textures) {
  48777. this._effect.setTexture(name, this._textures[name]);
  48778. }
  48779. // Texture arrays
  48780. for (name in this._textureArrays) {
  48781. this._effect.setTextureArray(name, this._textureArrays[name]);
  48782. }
  48783. // Int
  48784. for (name in this._ints) {
  48785. this._effect.setInt(name, this._ints[name]);
  48786. }
  48787. // Float
  48788. for (name in this._floats) {
  48789. this._effect.setFloat(name, this._floats[name]);
  48790. }
  48791. // Floats
  48792. for (name in this._floatsArrays) {
  48793. this._effect.setArray(name, this._floatsArrays[name]);
  48794. }
  48795. // Color3
  48796. for (name in this._colors3) {
  48797. this._effect.setColor3(name, this._colors3[name]);
  48798. }
  48799. for (name in this._colors3Arrays) {
  48800. this._effect.setArray3(name, this._colors3Arrays[name]);
  48801. }
  48802. // Color4
  48803. for (name in this._colors4) {
  48804. var color = this._colors4[name];
  48805. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  48806. }
  48807. // Vector2
  48808. for (name in this._vectors2) {
  48809. this._effect.setVector2(name, this._vectors2[name]);
  48810. }
  48811. // Vector3
  48812. for (name in this._vectors3) {
  48813. this._effect.setVector3(name, this._vectors3[name]);
  48814. }
  48815. // Vector4
  48816. for (name in this._vectors4) {
  48817. this._effect.setVector4(name, this._vectors4[name]);
  48818. }
  48819. // Matrix
  48820. for (name in this._matrices) {
  48821. this._effect.setMatrix(name, this._matrices[name]);
  48822. }
  48823. // Matrix 3x3
  48824. for (name in this._matrices3x3) {
  48825. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  48826. }
  48827. // Matrix 2x2
  48828. for (name in this._matrices2x2) {
  48829. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  48830. }
  48831. // Vector2Array
  48832. for (name in this._vectors2Arrays) {
  48833. this._effect.setArray2(name, this._vectors2Arrays[name]);
  48834. }
  48835. // Vector3Array
  48836. for (name in this._vectors3Arrays) {
  48837. this._effect.setArray3(name, this._vectors3Arrays[name]);
  48838. }
  48839. }
  48840. this._afterBind(mesh);
  48841. };
  48842. ShaderMaterial.prototype.getActiveTextures = function () {
  48843. var activeTextures = _super.prototype.getActiveTextures.call(this);
  48844. for (var name in this._textures) {
  48845. activeTextures.push(this._textures[name]);
  48846. }
  48847. for (var name in this._textureArrays) {
  48848. var array = this._textureArrays[name];
  48849. for (var index = 0; index < array.length; index++) {
  48850. activeTextures.push(array[index]);
  48851. }
  48852. }
  48853. return activeTextures;
  48854. };
  48855. ShaderMaterial.prototype.hasTexture = function (texture) {
  48856. if (_super.prototype.hasTexture.call(this, texture)) {
  48857. return true;
  48858. }
  48859. for (var name in this._textures) {
  48860. if (this._textures[name] === texture) {
  48861. return true;
  48862. }
  48863. }
  48864. for (var name in this._textureArrays) {
  48865. var array = this._textureArrays[name];
  48866. for (var index = 0; index < array.length; index++) {
  48867. if (array[index] === texture) {
  48868. return true;
  48869. }
  48870. }
  48871. }
  48872. return false;
  48873. };
  48874. ShaderMaterial.prototype.clone = function (name) {
  48875. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  48876. return newShaderMaterial;
  48877. };
  48878. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  48879. if (forceDisposeTextures) {
  48880. var name;
  48881. for (name in this._textures) {
  48882. this._textures[name].dispose();
  48883. }
  48884. for (name in this._textureArrays) {
  48885. var array = this._textureArrays[name];
  48886. for (var index = 0; index < array.length; index++) {
  48887. array[index].dispose();
  48888. }
  48889. }
  48890. }
  48891. this._textures = {};
  48892. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  48893. };
  48894. ShaderMaterial.prototype.serialize = function () {
  48895. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  48896. serializationObject.customType = "BABYLON.ShaderMaterial";
  48897. serializationObject.options = this._options;
  48898. serializationObject.shaderPath = this._shaderPath;
  48899. var name;
  48900. // Texture
  48901. serializationObject.textures = {};
  48902. for (name in this._textures) {
  48903. serializationObject.textures[name] = this._textures[name].serialize();
  48904. }
  48905. // Texture arrays
  48906. serializationObject.textureArrays = {};
  48907. for (name in this._textureArrays) {
  48908. serializationObject.textureArrays[name] = [];
  48909. var array = this._textureArrays[name];
  48910. for (var index = 0; index < array.length; index++) {
  48911. serializationObject.textureArrays[name].push(array[index].serialize());
  48912. }
  48913. }
  48914. // Float
  48915. serializationObject.floats = {};
  48916. for (name in this._floats) {
  48917. serializationObject.floats[name] = this._floats[name];
  48918. }
  48919. // Float s
  48920. serializationObject.FloatArrays = {};
  48921. for (name in this._floatsArrays) {
  48922. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  48923. }
  48924. // Color3
  48925. serializationObject.colors3 = {};
  48926. for (name in this._colors3) {
  48927. serializationObject.colors3[name] = this._colors3[name].asArray();
  48928. }
  48929. // Color3 array
  48930. serializationObject.colors3Arrays = {};
  48931. for (name in this._colors3Arrays) {
  48932. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  48933. }
  48934. // Color4
  48935. serializationObject.colors4 = {};
  48936. for (name in this._colors4) {
  48937. serializationObject.colors4[name] = this._colors4[name].asArray();
  48938. }
  48939. // Vector2
  48940. serializationObject.vectors2 = {};
  48941. for (name in this._vectors2) {
  48942. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  48943. }
  48944. // Vector3
  48945. serializationObject.vectors3 = {};
  48946. for (name in this._vectors3) {
  48947. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  48948. }
  48949. // Vector4
  48950. serializationObject.vectors4 = {};
  48951. for (name in this._vectors4) {
  48952. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  48953. }
  48954. // Matrix
  48955. serializationObject.matrices = {};
  48956. for (name in this._matrices) {
  48957. serializationObject.matrices[name] = this._matrices[name].asArray();
  48958. }
  48959. // Matrix 3x3
  48960. serializationObject.matrices3x3 = {};
  48961. for (name in this._matrices3x3) {
  48962. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  48963. }
  48964. // Matrix 2x2
  48965. serializationObject.matrices2x2 = {};
  48966. for (name in this._matrices2x2) {
  48967. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  48968. }
  48969. // Vector2Array
  48970. serializationObject.vectors2Arrays = {};
  48971. for (name in this._vectors2Arrays) {
  48972. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  48973. }
  48974. // Vector3Array
  48975. serializationObject.vectors3Arrays = {};
  48976. for (name in this._vectors3Arrays) {
  48977. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  48978. }
  48979. return serializationObject;
  48980. };
  48981. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  48982. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  48983. var name;
  48984. // Texture
  48985. for (name in source.textures) {
  48986. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  48987. }
  48988. // Texture arrays
  48989. for (name in source.textureArrays) {
  48990. var array = source.textureArrays[name];
  48991. var textureArray = new Array();
  48992. for (var index = 0; index < array.length; index++) {
  48993. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  48994. }
  48995. material.setTextureArray(name, textureArray);
  48996. }
  48997. // Float
  48998. for (name in source.floats) {
  48999. material.setFloat(name, source.floats[name]);
  49000. }
  49001. // Float s
  49002. for (name in source.floatsArrays) {
  49003. material.setFloats(name, source.floatsArrays[name]);
  49004. }
  49005. // Color3
  49006. for (name in source.colors3) {
  49007. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  49008. }
  49009. // Color3 arrays
  49010. for (name in source.colors3Arrays) {
  49011. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  49012. if (i % 3 === 0) {
  49013. arr.push([num]);
  49014. }
  49015. else {
  49016. arr[arr.length - 1].push(num);
  49017. }
  49018. return arr;
  49019. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  49020. material.setColor3Array(name, colors);
  49021. }
  49022. // Color4
  49023. for (name in source.colors4) {
  49024. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  49025. }
  49026. // Vector2
  49027. for (name in source.vectors2) {
  49028. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  49029. }
  49030. // Vector3
  49031. for (name in source.vectors3) {
  49032. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  49033. }
  49034. // Vector4
  49035. for (name in source.vectors4) {
  49036. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  49037. }
  49038. // Matrix
  49039. for (name in source.matrices) {
  49040. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  49041. }
  49042. // Matrix 3x3
  49043. for (name in source.matrices3x3) {
  49044. material.setMatrix3x3(name, source.matrices3x3[name]);
  49045. }
  49046. // Matrix 2x2
  49047. for (name in source.matrices2x2) {
  49048. material.setMatrix2x2(name, source.matrices2x2[name]);
  49049. }
  49050. // Vector2Array
  49051. for (name in source.vectors2Arrays) {
  49052. material.setArray2(name, source.vectors2Arrays[name]);
  49053. }
  49054. // Vector3Array
  49055. for (name in source.vectors3Arrays) {
  49056. material.setArray3(name, source.vectors3Arrays[name]);
  49057. }
  49058. return material;
  49059. };
  49060. return ShaderMaterial;
  49061. }(BABYLON.Material));
  49062. BABYLON.ShaderMaterial = ShaderMaterial;
  49063. })(BABYLON || (BABYLON = {}));
  49064. //# sourceMappingURL=babylon.shaderMaterial.js.map
  49065. var BABYLON;
  49066. (function (BABYLON) {
  49067. var MeshBuilder = /** @class */ (function () {
  49068. function MeshBuilder() {
  49069. }
  49070. MeshBuilder.updateSideOrientation = function (orientation) {
  49071. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  49072. return BABYLON.Mesh.DOUBLESIDE;
  49073. }
  49074. if (orientation === undefined || orientation === null) {
  49075. return BABYLON.Mesh.FRONTSIDE;
  49076. }
  49077. return orientation;
  49078. };
  49079. /**
  49080. * Creates a box mesh.
  49081. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  49082. * The parameter `size` sets the size (float) of each box side (default 1).
  49083. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  49084. * 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).
  49085. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  49086. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49087. * 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).
  49088. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49089. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49090. */
  49091. MeshBuilder.CreateBox = function (name, options, scene) {
  49092. if (scene === void 0) { scene = null; }
  49093. var box = new BABYLON.Mesh(name, scene);
  49094. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49095. box._originalBuilderSideOrientation = options.sideOrientation;
  49096. var vertexData = BABYLON.VertexData.CreateBox(options);
  49097. vertexData.applyToMesh(box, options.updatable);
  49098. return box;
  49099. };
  49100. /**
  49101. * Creates a sphere mesh.
  49102. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  49103. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  49104. * 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`).
  49105. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  49106. * 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
  49107. * 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).
  49108. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49109. * 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).
  49110. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49111. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49112. */
  49113. MeshBuilder.CreateSphere = function (name, options, scene) {
  49114. var sphere = new BABYLON.Mesh(name, scene);
  49115. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49116. sphere._originalBuilderSideOrientation = options.sideOrientation;
  49117. var vertexData = BABYLON.VertexData.CreateSphere(options);
  49118. vertexData.applyToMesh(sphere, options.updatable);
  49119. return sphere;
  49120. };
  49121. /**
  49122. * Creates a plane polygonal mesh. By default, this is a disc.
  49123. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  49124. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  49125. * 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.
  49126. * 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
  49127. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49128. * 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).
  49129. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49130. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49131. */
  49132. MeshBuilder.CreateDisc = function (name, options, scene) {
  49133. if (scene === void 0) { scene = null; }
  49134. var disc = new BABYLON.Mesh(name, scene);
  49135. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49136. disc._originalBuilderSideOrientation = options.sideOrientation;
  49137. var vertexData = BABYLON.VertexData.CreateDisc(options);
  49138. vertexData.applyToMesh(disc, options.updatable);
  49139. return disc;
  49140. };
  49141. /**
  49142. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  49143. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  49144. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  49145. * 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`).
  49146. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  49147. * 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.
  49148. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49149. * 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).
  49150. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49151. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49152. */
  49153. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  49154. var sphere = new BABYLON.Mesh(name, scene);
  49155. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49156. sphere._originalBuilderSideOrientation = options.sideOrientation;
  49157. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  49158. vertexData.applyToMesh(sphere, options.updatable);
  49159. return sphere;
  49160. };
  49161. ;
  49162. /**
  49163. * Creates a ribbon mesh.
  49164. * 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.
  49165. *
  49166. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  49167. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  49168. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  49169. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  49170. * 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.
  49171. * 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.
  49172. * 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
  49173. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49174. * 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).
  49175. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49176. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  49177. * 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.
  49178. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  49179. * 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
  49180. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  49181. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  49182. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49183. */
  49184. MeshBuilder.CreateRibbon = function (name, options, scene) {
  49185. if (scene === void 0) { scene = null; }
  49186. var pathArray = options.pathArray;
  49187. var closeArray = options.closeArray;
  49188. var closePath = options.closePath;
  49189. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49190. var instance = options.instance;
  49191. var updatable = options.updatable;
  49192. if (instance) {
  49193. // positionFunction : ribbon case
  49194. // only pathArray and sideOrientation parameters are taken into account for positions update
  49195. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  49196. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  49197. var positionFunction = function (positions) {
  49198. var minlg = pathArray[0].length;
  49199. var i = 0;
  49200. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  49201. for (var si = 1; si <= ns; si++) {
  49202. for (var p = 0; p < pathArray.length; p++) {
  49203. var path = pathArray[p];
  49204. var l = path.length;
  49205. minlg = (minlg < l) ? minlg : l;
  49206. var j = 0;
  49207. while (j < minlg) {
  49208. positions[i] = path[j].x;
  49209. positions[i + 1] = path[j].y;
  49210. positions[i + 2] = path[j].z;
  49211. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  49212. BABYLON.Tmp.Vector3[0].x = path[j].x;
  49213. }
  49214. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  49215. BABYLON.Tmp.Vector3[1].x = path[j].x;
  49216. }
  49217. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  49218. BABYLON.Tmp.Vector3[0].y = path[j].y;
  49219. }
  49220. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  49221. BABYLON.Tmp.Vector3[1].y = path[j].y;
  49222. }
  49223. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  49224. BABYLON.Tmp.Vector3[0].z = path[j].z;
  49225. }
  49226. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  49227. BABYLON.Tmp.Vector3[1].z = path[j].z;
  49228. }
  49229. j++;
  49230. i += 3;
  49231. }
  49232. if (instance._closePath) {
  49233. positions[i] = path[0].x;
  49234. positions[i + 1] = path[0].y;
  49235. positions[i + 2] = path[0].z;
  49236. i += 3;
  49237. }
  49238. }
  49239. }
  49240. };
  49241. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49242. positionFunction(positions);
  49243. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  49244. instance._boundingInfo.update(instance._worldMatrix);
  49245. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  49246. if (options.colors) {
  49247. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49248. for (var c = 0; c < options.colors.length; c++) {
  49249. colors[c * 4] = options.colors[c].r;
  49250. colors[c * 4 + 1] = options.colors[c].g;
  49251. colors[c * 4 + 2] = options.colors[c].b;
  49252. colors[c * 4 + 3] = options.colors[c].a;
  49253. }
  49254. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  49255. }
  49256. if (options.uvs) {
  49257. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49258. for (var i = 0; i < options.uvs.length; i++) {
  49259. uvs[i * 2] = options.uvs[i].x;
  49260. uvs[i * 2 + 1] = options.uvs[i].y;
  49261. }
  49262. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  49263. }
  49264. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  49265. var indices = instance.getIndices();
  49266. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49267. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  49268. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  49269. if (instance._closePath) {
  49270. var indexFirst = 0;
  49271. var indexLast = 0;
  49272. for (var p = 0; p < pathArray.length; p++) {
  49273. indexFirst = instance._idx[p] * 3;
  49274. if (p + 1 < pathArray.length) {
  49275. indexLast = (instance._idx[p + 1] - 1) * 3;
  49276. }
  49277. else {
  49278. indexLast = normals.length - 3;
  49279. }
  49280. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  49281. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  49282. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  49283. normals[indexLast] = normals[indexFirst];
  49284. normals[indexLast + 1] = normals[indexFirst + 1];
  49285. normals[indexLast + 2] = normals[indexFirst + 2];
  49286. }
  49287. }
  49288. if (!(instance.areNormalsFrozen)) {
  49289. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  49290. }
  49291. }
  49292. return instance;
  49293. }
  49294. else {
  49295. var ribbon = new BABYLON.Mesh(name, scene);
  49296. ribbon._originalBuilderSideOrientation = sideOrientation;
  49297. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  49298. if (closePath) {
  49299. ribbon._idx = vertexData._idx;
  49300. }
  49301. ribbon._closePath = closePath;
  49302. ribbon._closeArray = closeArray;
  49303. vertexData.applyToMesh(ribbon, updatable);
  49304. return ribbon;
  49305. }
  49306. };
  49307. /**
  49308. * Creates a cylinder or a cone mesh.
  49309. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  49310. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  49311. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  49312. * 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.
  49313. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  49314. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  49315. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  49316. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  49317. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  49318. * 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).
  49319. * 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
  49320. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  49321. * 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
  49322. * 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.
  49323. * If `enclose` is false, a ring surface is one element.
  49324. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  49325. * 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
  49326. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49327. * 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).
  49328. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49329. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49330. */
  49331. MeshBuilder.CreateCylinder = function (name, options, scene) {
  49332. var cylinder = new BABYLON.Mesh(name, scene);
  49333. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49334. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  49335. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  49336. vertexData.applyToMesh(cylinder, options.updatable);
  49337. return cylinder;
  49338. };
  49339. /**
  49340. * Creates a torus mesh.
  49341. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  49342. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  49343. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  49344. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  49345. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49346. * 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).
  49347. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49348. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49349. */
  49350. MeshBuilder.CreateTorus = function (name, options, scene) {
  49351. var torus = new BABYLON.Mesh(name, scene);
  49352. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49353. torus._originalBuilderSideOrientation = options.sideOrientation;
  49354. var vertexData = BABYLON.VertexData.CreateTorus(options);
  49355. vertexData.applyToMesh(torus, options.updatable);
  49356. return torus;
  49357. };
  49358. /**
  49359. * Creates a torus knot mesh.
  49360. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  49361. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  49362. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  49363. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  49364. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  49365. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49366. * 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).
  49367. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49368. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49369. */
  49370. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  49371. var torusKnot = new BABYLON.Mesh(name, scene);
  49372. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49373. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  49374. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  49375. vertexData.applyToMesh(torusKnot, options.updatable);
  49376. return torusKnot;
  49377. };
  49378. /**
  49379. * Creates a line system mesh.
  49380. * A line system is a pool of many lines gathered in a single mesh.
  49381. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  49382. * 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.
  49383. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  49384. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  49385. * 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
  49386. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  49387. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  49388. * 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
  49389. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  49390. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49391. */
  49392. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  49393. var instance = options.instance;
  49394. var lines = options.lines;
  49395. var colors = options.colors;
  49396. if (instance) {
  49397. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49398. var vertexColor;
  49399. var lineColors;
  49400. if (colors) {
  49401. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49402. }
  49403. var i = 0;
  49404. var c = 0;
  49405. for (var l = 0; l < lines.length; l++) {
  49406. var points = lines[l];
  49407. for (var p = 0; p < points.length; p++) {
  49408. positions[i] = points[p].x;
  49409. positions[i + 1] = points[p].y;
  49410. positions[i + 2] = points[p].z;
  49411. if (colors && vertexColor) {
  49412. lineColors = colors[l];
  49413. vertexColor[c] = lineColors[p].r;
  49414. vertexColor[c + 1] = lineColors[p].g;
  49415. vertexColor[c + 2] = lineColors[p].b;
  49416. vertexColor[c + 3] = lineColors[p].a;
  49417. c += 4;
  49418. }
  49419. i += 3;
  49420. }
  49421. }
  49422. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  49423. if (colors && vertexColor) {
  49424. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  49425. }
  49426. return instance;
  49427. }
  49428. // line system creation
  49429. var useVertexColor = (colors) ? true : false;
  49430. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  49431. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  49432. vertexData.applyToMesh(lineSystem, options.updatable);
  49433. return lineSystem;
  49434. };
  49435. /**
  49436. * Creates a line mesh.
  49437. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  49438. * 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.
  49439. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  49440. * The parameter `points` is an array successive Vector3.
  49441. * 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
  49442. * The optional parameter `colors` is an array of successive Color4, one per line point.
  49443. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  49444. * When updating an instance, remember that only point positions can change, not the number of points.
  49445. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49446. */
  49447. MeshBuilder.CreateLines = function (name, options, scene) {
  49448. if (scene === void 0) { scene = null; }
  49449. var colors = (options.colors) ? [options.colors] : null;
  49450. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  49451. return lines;
  49452. };
  49453. /**
  49454. * Creates a dashed line mesh.
  49455. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  49456. * 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.
  49457. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  49458. * The parameter `points` is an array successive Vector3.
  49459. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  49460. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  49461. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  49462. * 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
  49463. * When updating an instance, remember that only point positions can change, not the number of points.
  49464. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49465. */
  49466. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  49467. if (scene === void 0) { scene = null; }
  49468. var points = options.points;
  49469. var instance = options.instance;
  49470. var gapSize = options.gapSize || 1;
  49471. var dashSize = options.dashSize || 3;
  49472. if (instance) {
  49473. var positionFunction = function (positions) {
  49474. var curvect = BABYLON.Vector3.Zero();
  49475. var nbSeg = positions.length / 6;
  49476. var lg = 0;
  49477. var nb = 0;
  49478. var shft = 0;
  49479. var dashshft = 0;
  49480. var curshft = 0;
  49481. var p = 0;
  49482. var i = 0;
  49483. var j = 0;
  49484. for (i = 0; i < points.length - 1; i++) {
  49485. points[i + 1].subtractToRef(points[i], curvect);
  49486. lg += curvect.length();
  49487. }
  49488. shft = lg / nbSeg;
  49489. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  49490. for (i = 0; i < points.length - 1; i++) {
  49491. points[i + 1].subtractToRef(points[i], curvect);
  49492. nb = Math.floor(curvect.length() / shft);
  49493. curvect.normalize();
  49494. j = 0;
  49495. while (j < nb && p < positions.length) {
  49496. curshft = shft * j;
  49497. positions[p] = points[i].x + curshft * curvect.x;
  49498. positions[p + 1] = points[i].y + curshft * curvect.y;
  49499. positions[p + 2] = points[i].z + curshft * curvect.z;
  49500. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  49501. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  49502. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  49503. p += 6;
  49504. j++;
  49505. }
  49506. }
  49507. while (p < positions.length) {
  49508. positions[p] = points[i].x;
  49509. positions[p + 1] = points[i].y;
  49510. positions[p + 2] = points[i].z;
  49511. p += 3;
  49512. }
  49513. };
  49514. instance.updateMeshPositions(positionFunction, false);
  49515. return instance;
  49516. }
  49517. // dashed lines creation
  49518. var dashedLines = new BABYLON.LinesMesh(name, scene);
  49519. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  49520. vertexData.applyToMesh(dashedLines, options.updatable);
  49521. dashedLines.dashSize = dashSize;
  49522. dashedLines.gapSize = gapSize;
  49523. return dashedLines;
  49524. };
  49525. /**
  49526. * Creates an extruded shape mesh.
  49527. * 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.
  49528. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  49529. *
  49530. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  49531. * 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
  49532. * extruded along the Z axis.
  49533. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  49534. * 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.
  49535. * The parameter `scale` (float, default 1) is the value to scale the shape.
  49536. * 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
  49537. * 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
  49538. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  49539. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49540. * 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).
  49541. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49542. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  49543. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49544. */
  49545. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  49546. if (scene === void 0) { scene = null; }
  49547. var path = options.path;
  49548. var shape = options.shape;
  49549. var scale = options.scale || 1;
  49550. var rotation = options.rotation || 0;
  49551. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  49552. var updatable = options.updatable;
  49553. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49554. var instance = options.instance || null;
  49555. var invertUV = options.invertUV || false;
  49556. 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);
  49557. };
  49558. /**
  49559. * Creates an custom extruded shape mesh.
  49560. * 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.
  49561. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  49562. *
  49563. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  49564. * 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
  49565. * extruded along the Z axis.
  49566. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  49567. * 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
  49568. * and the distance of this point from the begining of the path :
  49569. * ```javascript
  49570. * var rotationFunction = function(i, distance) {
  49571. * // do things
  49572. * return rotationValue; }
  49573. * ```
  49574. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  49575. * 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
  49576. * and the distance of this point from the begining of the path :
  49577. * ```javascript
  49578. * var scaleFunction = function(i, distance) {
  49579. * // do things
  49580. * return scaleValue;}
  49581. * ```
  49582. * It must returns a float value that will be the scale value applied to the shape on each path point.
  49583. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  49584. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  49585. * 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
  49586. * 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
  49587. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  49588. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49589. * 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).
  49590. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49591. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  49592. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49593. */
  49594. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  49595. var path = options.path;
  49596. var shape = options.shape;
  49597. var scaleFunction = options.scaleFunction || (function () { return 1; });
  49598. var rotationFunction = options.rotationFunction || (function () { return 0; });
  49599. var ribbonCloseArray = options.ribbonCloseArray || false;
  49600. var ribbonClosePath = options.ribbonClosePath || false;
  49601. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  49602. var updatable = options.updatable;
  49603. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49604. var instance = options.instance;
  49605. var invertUV = options.invertUV || false;
  49606. 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);
  49607. };
  49608. /**
  49609. * Creates lathe mesh.
  49610. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  49611. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  49612. *
  49613. * 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
  49614. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  49615. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  49616. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  49617. * 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.
  49618. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  49619. * 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
  49620. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49621. * 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).
  49622. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49623. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  49624. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49625. */
  49626. MeshBuilder.CreateLathe = function (name, options, scene) {
  49627. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  49628. var closed = (options.closed === undefined) ? true : options.closed;
  49629. var shape = options.shape;
  49630. var radius = options.radius || 1;
  49631. var tessellation = options.tessellation || 64;
  49632. var updatable = options.updatable;
  49633. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49634. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  49635. var pi2 = Math.PI * 2;
  49636. var paths = new Array();
  49637. var invertUV = options.invertUV || false;
  49638. var i = 0;
  49639. var p = 0;
  49640. var step = pi2 / tessellation * arc;
  49641. var rotated;
  49642. var path = new Array();
  49643. ;
  49644. for (i = 0; i <= tessellation; i++) {
  49645. var path = [];
  49646. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  49647. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  49648. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  49649. }
  49650. for (p = 0; p < shape.length; p++) {
  49651. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  49652. path.push(rotated);
  49653. }
  49654. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  49655. 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));
  49656. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  49657. }
  49658. paths.push(path);
  49659. }
  49660. // lathe ribbon
  49661. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  49662. return lathe;
  49663. };
  49664. /**
  49665. * Creates a plane mesh.
  49666. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  49667. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  49668. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  49669. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  49670. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49671. * 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).
  49672. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49673. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49674. */
  49675. MeshBuilder.CreatePlane = function (name, options, scene) {
  49676. var plane = new BABYLON.Mesh(name, scene);
  49677. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49678. plane._originalBuilderSideOrientation = options.sideOrientation;
  49679. var vertexData = BABYLON.VertexData.CreatePlane(options);
  49680. vertexData.applyToMesh(plane, options.updatable);
  49681. if (options.sourcePlane) {
  49682. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  49683. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  49684. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  49685. plane.rotate(vectorProduct, product);
  49686. }
  49687. return plane;
  49688. };
  49689. /**
  49690. * Creates a ground mesh.
  49691. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  49692. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  49693. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  49694. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49695. */
  49696. MeshBuilder.CreateGround = function (name, options, scene) {
  49697. var ground = new BABYLON.GroundMesh(name, scene);
  49698. ground._setReady(false);
  49699. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  49700. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  49701. ground._width = options.width || 1;
  49702. ground._height = options.height || 1;
  49703. ground._maxX = ground._width / 2;
  49704. ground._maxZ = ground._height / 2;
  49705. ground._minX = -ground._maxX;
  49706. ground._minZ = -ground._maxZ;
  49707. var vertexData = BABYLON.VertexData.CreateGround(options);
  49708. vertexData.applyToMesh(ground, options.updatable);
  49709. ground._setReady(true);
  49710. return ground;
  49711. };
  49712. /**
  49713. * Creates a tiled ground mesh.
  49714. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  49715. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  49716. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  49717. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  49718. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  49719. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  49720. * numbers of subdivisions on the ground width and height of each tile.
  49721. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49722. */
  49723. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  49724. var tiledGround = new BABYLON.Mesh(name, scene);
  49725. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  49726. vertexData.applyToMesh(tiledGround, options.updatable);
  49727. return tiledGround;
  49728. };
  49729. /**
  49730. * Creates a ground mesh from a height map.
  49731. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  49732. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  49733. * The parameter `url` sets the URL of the height map image resource.
  49734. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  49735. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  49736. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  49737. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  49738. * 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.
  49739. * 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).
  49740. * This function is passed the newly built mesh :
  49741. * ```javascript
  49742. * function(mesh) { // do things
  49743. * return; }
  49744. * ```
  49745. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49746. */
  49747. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  49748. var width = options.width || 10.0;
  49749. var height = options.height || 10.0;
  49750. var subdivisions = options.subdivisions || 1 | 0;
  49751. var minHeight = options.minHeight || 0.0;
  49752. var maxHeight = options.maxHeight || 1.0;
  49753. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  49754. var updatable = options.updatable;
  49755. var onReady = options.onReady;
  49756. var ground = new BABYLON.GroundMesh(name, scene);
  49757. ground._subdivisionsX = subdivisions;
  49758. ground._subdivisionsY = subdivisions;
  49759. ground._width = width;
  49760. ground._height = height;
  49761. ground._maxX = ground._width / 2.0;
  49762. ground._maxZ = ground._height / 2.0;
  49763. ground._minX = -ground._maxX;
  49764. ground._minZ = -ground._maxZ;
  49765. ground._setReady(false);
  49766. var onload = function (img) {
  49767. // Getting height map data
  49768. var canvas = document.createElement("canvas");
  49769. var context = canvas.getContext("2d");
  49770. if (!context) {
  49771. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  49772. }
  49773. var bufferWidth = img.width;
  49774. var bufferHeight = img.height;
  49775. canvas.width = bufferWidth;
  49776. canvas.height = bufferHeight;
  49777. context.drawImage(img, 0, 0);
  49778. // Create VertexData from map data
  49779. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  49780. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  49781. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  49782. width: width, height: height,
  49783. subdivisions: subdivisions,
  49784. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  49785. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  49786. });
  49787. vertexData.applyToMesh(ground, updatable);
  49788. ground._setReady(true);
  49789. //execute ready callback, if set
  49790. if (onReady) {
  49791. onReady(ground);
  49792. }
  49793. };
  49794. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  49795. return ground;
  49796. };
  49797. /**
  49798. * Creates a polygon mesh.
  49799. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  49800. * 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.
  49801. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49802. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49803. * 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).
  49804. * Remember you can only change the shape positions, not their number when updating a polygon.
  49805. */
  49806. MeshBuilder.CreatePolygon = function (name, options, scene) {
  49807. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49808. var shape = options.shape;
  49809. var holes = options.holes || [];
  49810. var depth = options.depth || 0;
  49811. var contours = [];
  49812. var hole = [];
  49813. for (var i = 0; i < shape.length; i++) {
  49814. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  49815. }
  49816. var epsilon = 0.00000001;
  49817. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  49818. contours.pop();
  49819. }
  49820. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  49821. for (var hNb = 0; hNb < holes.length; hNb++) {
  49822. hole = [];
  49823. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  49824. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  49825. }
  49826. polygonTriangulation.addHole(hole);
  49827. }
  49828. var polygon = polygonTriangulation.build(options.updatable, depth);
  49829. polygon._originalBuilderSideOrientation = options.sideOrientation;
  49830. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  49831. vertexData.applyToMesh(polygon, options.updatable);
  49832. return polygon;
  49833. };
  49834. ;
  49835. /**
  49836. * Creates an extruded polygon mesh, with depth in the Y direction.
  49837. * 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).
  49838. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  49839. */
  49840. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  49841. return MeshBuilder.CreatePolygon(name, options, scene);
  49842. };
  49843. ;
  49844. /**
  49845. * Creates a tube mesh.
  49846. * 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.
  49847. *
  49848. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  49849. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  49850. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  49851. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  49852. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  49853. * 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.
  49854. * It must return a radius value (positive float) :
  49855. * ```javascript
  49856. * var radiusFunction = function(i, distance) {
  49857. * // do things
  49858. * return radius; }
  49859. * ```
  49860. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  49861. * 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
  49862. * 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
  49863. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49864. * 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).
  49865. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49866. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  49867. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49868. */
  49869. MeshBuilder.CreateTube = function (name, options, scene) {
  49870. var path = options.path;
  49871. var instance = options.instance;
  49872. var radius = 1.0;
  49873. if (instance) {
  49874. radius = instance.radius;
  49875. }
  49876. if (options.radius !== undefined) {
  49877. radius = options.radius;
  49878. }
  49879. ;
  49880. var tessellation = options.tessellation || 64 | 0;
  49881. var radiusFunction = options.radiusFunction || null;
  49882. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  49883. var invertUV = options.invertUV || false;
  49884. var updatable = options.updatable;
  49885. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49886. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  49887. // tube geometry
  49888. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  49889. var tangents = path3D.getTangents();
  49890. var normals = path3D.getNormals();
  49891. var distances = path3D.getDistances();
  49892. var pi2 = Math.PI * 2;
  49893. var step = pi2 / tessellation * arc;
  49894. var returnRadius = function () { return radius; };
  49895. var radiusFunctionFinal = radiusFunction || returnRadius;
  49896. var circlePath;
  49897. var rad;
  49898. var normal;
  49899. var rotated;
  49900. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  49901. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  49902. for (var i = 0; i < path.length; i++) {
  49903. rad = radiusFunctionFinal(i, distances[i]); // current radius
  49904. circlePath = Array(); // current circle array
  49905. normal = normals[i]; // current normal
  49906. for (var t = 0; t < tessellation; t++) {
  49907. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  49908. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  49909. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  49910. rotated.scaleInPlace(rad).addInPlace(path[i]);
  49911. circlePath[t] = rotated;
  49912. }
  49913. circlePaths[index] = circlePath;
  49914. index++;
  49915. }
  49916. // cap
  49917. var capPath = function (nbPoints, pathIndex) {
  49918. var pointCap = Array();
  49919. for (var i = 0; i < nbPoints; i++) {
  49920. pointCap.push(path[pathIndex]);
  49921. }
  49922. return pointCap;
  49923. };
  49924. switch (cap) {
  49925. case BABYLON.Mesh.NO_CAP:
  49926. break;
  49927. case BABYLON.Mesh.CAP_START:
  49928. circlePaths[0] = capPath(tessellation, 0);
  49929. circlePaths[1] = circlePaths[2].slice(0);
  49930. break;
  49931. case BABYLON.Mesh.CAP_END:
  49932. circlePaths[index] = circlePaths[index - 1].slice(0);
  49933. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  49934. break;
  49935. case BABYLON.Mesh.CAP_ALL:
  49936. circlePaths[0] = capPath(tessellation, 0);
  49937. circlePaths[1] = circlePaths[2].slice(0);
  49938. circlePaths[index] = circlePaths[index - 1].slice(0);
  49939. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  49940. break;
  49941. default:
  49942. break;
  49943. }
  49944. return circlePaths;
  49945. };
  49946. var path3D;
  49947. var pathArray;
  49948. if (instance) {
  49949. var arc = options.arc || instance.arc;
  49950. path3D = (instance.path3D).update(path);
  49951. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  49952. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  49953. instance.path3D = path3D;
  49954. instance.pathArray = pathArray;
  49955. instance.arc = arc;
  49956. instance.radius = radius;
  49957. return instance;
  49958. }
  49959. // tube creation
  49960. path3D = new BABYLON.Path3D(path);
  49961. var newPathArray = new Array();
  49962. cap = (cap < 0 || cap > 3) ? 0 : cap;
  49963. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  49964. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  49965. tube.pathArray = pathArray;
  49966. tube.path3D = path3D;
  49967. tube.tessellation = tessellation;
  49968. tube.cap = cap;
  49969. tube.arc = options.arc;
  49970. tube.radius = radius;
  49971. return tube;
  49972. };
  49973. /**
  49974. * Creates a polyhedron mesh.
  49975. *
  49976. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  49977. * 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
  49978. * to choose the wanted type.
  49979. * The parameter `size` (positive float, default 1) sets the polygon size.
  49980. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  49981. * 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`.
  49982. * 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
  49983. * 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)`).
  49984. * 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
  49985. * 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.
  49986. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49987. * 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).
  49988. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49989. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49990. */
  49991. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  49992. var polyhedron = new BABYLON.Mesh(name, scene);
  49993. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49994. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  49995. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  49996. vertexData.applyToMesh(polyhedron, options.updatable);
  49997. return polyhedron;
  49998. };
  49999. /**
  50000. * Creates a decal mesh.
  50001. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  50002. * 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.
  50003. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  50004. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  50005. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  50006. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  50007. */
  50008. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  50009. var indices = sourceMesh.getIndices();
  50010. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50011. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50012. var position = options.position || BABYLON.Vector3.Zero();
  50013. var normal = options.normal || BABYLON.Vector3.Up();
  50014. var size = options.size || BABYLON.Vector3.One();
  50015. var angle = options.angle || 0;
  50016. // Getting correct rotation
  50017. if (!normal) {
  50018. var target = new BABYLON.Vector3(0, 0, 1);
  50019. var camera = sourceMesh.getScene().activeCamera;
  50020. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  50021. normal = camera.globalPosition.subtract(cameraWorldTarget);
  50022. }
  50023. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  50024. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  50025. var pitch = Math.atan2(normal.y, len);
  50026. // Matrix
  50027. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  50028. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  50029. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  50030. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  50031. var vertexData = new BABYLON.VertexData();
  50032. vertexData.indices = [];
  50033. vertexData.positions = [];
  50034. vertexData.normals = [];
  50035. vertexData.uvs = [];
  50036. var currentVertexDataIndex = 0;
  50037. var extractDecalVector3 = function (indexId) {
  50038. var result = new BABYLON.PositionNormalVertex();
  50039. if (!indices || !positions || !normals) {
  50040. return result;
  50041. }
  50042. var vertexId = indices[indexId];
  50043. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  50044. // Send vector to decal local world
  50045. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  50046. // Get normal
  50047. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  50048. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  50049. return result;
  50050. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  50051. var clip = function (vertices, axis) {
  50052. if (vertices.length === 0) {
  50053. return vertices;
  50054. }
  50055. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  50056. var clipVertices = function (v0, v1) {
  50057. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  50058. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  50059. };
  50060. var result = new Array();
  50061. for (var index = 0; index < vertices.length; index += 3) {
  50062. var v1Out;
  50063. var v2Out;
  50064. var v3Out;
  50065. var total = 0;
  50066. var nV1 = null;
  50067. var nV2 = null;
  50068. var nV3 = null;
  50069. var nV4 = null;
  50070. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  50071. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  50072. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  50073. v1Out = d1 > 0;
  50074. v2Out = d2 > 0;
  50075. v3Out = d3 > 0;
  50076. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  50077. switch (total) {
  50078. case 0:
  50079. result.push(vertices[index]);
  50080. result.push(vertices[index + 1]);
  50081. result.push(vertices[index + 2]);
  50082. break;
  50083. case 1:
  50084. if (v1Out) {
  50085. nV1 = vertices[index + 1];
  50086. nV2 = vertices[index + 2];
  50087. nV3 = clipVertices(vertices[index], nV1);
  50088. nV4 = clipVertices(vertices[index], nV2);
  50089. }
  50090. if (v2Out) {
  50091. nV1 = vertices[index];
  50092. nV2 = vertices[index + 2];
  50093. nV3 = clipVertices(vertices[index + 1], nV1);
  50094. nV4 = clipVertices(vertices[index + 1], nV2);
  50095. result.push(nV3);
  50096. result.push(nV2.clone());
  50097. result.push(nV1.clone());
  50098. result.push(nV2.clone());
  50099. result.push(nV3.clone());
  50100. result.push(nV4);
  50101. break;
  50102. }
  50103. if (v3Out) {
  50104. nV1 = vertices[index];
  50105. nV2 = vertices[index + 1];
  50106. nV3 = clipVertices(vertices[index + 2], nV1);
  50107. nV4 = clipVertices(vertices[index + 2], nV2);
  50108. }
  50109. if (nV1 && nV2 && nV3 && nV4) {
  50110. result.push(nV1.clone());
  50111. result.push(nV2.clone());
  50112. result.push(nV3);
  50113. result.push(nV4);
  50114. result.push(nV3.clone());
  50115. result.push(nV2.clone());
  50116. }
  50117. break;
  50118. case 2:
  50119. if (!v1Out) {
  50120. nV1 = vertices[index].clone();
  50121. nV2 = clipVertices(nV1, vertices[index + 1]);
  50122. nV3 = clipVertices(nV1, vertices[index + 2]);
  50123. result.push(nV1);
  50124. result.push(nV2);
  50125. result.push(nV3);
  50126. }
  50127. if (!v2Out) {
  50128. nV1 = vertices[index + 1].clone();
  50129. nV2 = clipVertices(nV1, vertices[index + 2]);
  50130. nV3 = clipVertices(nV1, vertices[index]);
  50131. result.push(nV1);
  50132. result.push(nV2);
  50133. result.push(nV3);
  50134. }
  50135. if (!v3Out) {
  50136. nV1 = vertices[index + 2].clone();
  50137. nV2 = clipVertices(nV1, vertices[index]);
  50138. nV3 = clipVertices(nV1, vertices[index + 1]);
  50139. result.push(nV1);
  50140. result.push(nV2);
  50141. result.push(nV3);
  50142. }
  50143. break;
  50144. case 3:
  50145. break;
  50146. }
  50147. }
  50148. return result;
  50149. };
  50150. for (var index = 0; index < indices.length; index += 3) {
  50151. var faceVertices = new Array();
  50152. faceVertices.push(extractDecalVector3(index));
  50153. faceVertices.push(extractDecalVector3(index + 1));
  50154. faceVertices.push(extractDecalVector3(index + 2));
  50155. // Clip
  50156. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  50157. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  50158. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  50159. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  50160. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  50161. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  50162. if (faceVertices.length === 0) {
  50163. continue;
  50164. }
  50165. // Add UVs and get back to world
  50166. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  50167. var vertex = faceVertices[vIndex];
  50168. //TODO check for Int32Array | Uint32Array | Uint16Array
  50169. vertexData.indices.push(currentVertexDataIndex);
  50170. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  50171. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  50172. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  50173. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  50174. currentVertexDataIndex++;
  50175. }
  50176. }
  50177. // Return mesh
  50178. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  50179. vertexData.applyToMesh(decal);
  50180. decal.position = position.clone();
  50181. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  50182. return decal;
  50183. };
  50184. // Privates
  50185. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  50186. // extrusion geometry
  50187. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  50188. var tangents = path3D.getTangents();
  50189. var normals = path3D.getNormals();
  50190. var binormals = path3D.getBinormals();
  50191. var distances = path3D.getDistances();
  50192. var angle = 0;
  50193. var returnScale = function () { return scale !== null ? scale : 1; };
  50194. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  50195. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  50196. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  50197. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  50198. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  50199. for (var i = 0; i < curve.length; i++) {
  50200. var shapePath = new Array();
  50201. var angleStep = rotate(i, distances[i]);
  50202. var scaleRatio = scl(i, distances[i]);
  50203. for (var p = 0; p < shape.length; p++) {
  50204. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  50205. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  50206. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  50207. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  50208. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  50209. shapePath[p] = rotated;
  50210. }
  50211. shapePaths[index] = shapePath;
  50212. angle += angleStep;
  50213. index++;
  50214. }
  50215. // cap
  50216. var capPath = function (shapePath) {
  50217. var pointCap = Array();
  50218. var barycenter = BABYLON.Vector3.Zero();
  50219. var i;
  50220. for (i = 0; i < shapePath.length; i++) {
  50221. barycenter.addInPlace(shapePath[i]);
  50222. }
  50223. barycenter.scaleInPlace(1.0 / shapePath.length);
  50224. for (i = 0; i < shapePath.length; i++) {
  50225. pointCap.push(barycenter);
  50226. }
  50227. return pointCap;
  50228. };
  50229. switch (cap) {
  50230. case BABYLON.Mesh.NO_CAP:
  50231. break;
  50232. case BABYLON.Mesh.CAP_START:
  50233. shapePaths[0] = capPath(shapePaths[2]);
  50234. shapePaths[1] = shapePaths[2];
  50235. break;
  50236. case BABYLON.Mesh.CAP_END:
  50237. shapePaths[index] = shapePaths[index - 1];
  50238. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  50239. break;
  50240. case BABYLON.Mesh.CAP_ALL:
  50241. shapePaths[0] = capPath(shapePaths[2]);
  50242. shapePaths[1] = shapePaths[2];
  50243. shapePaths[index] = shapePaths[index - 1];
  50244. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  50245. break;
  50246. default:
  50247. break;
  50248. }
  50249. return shapePaths;
  50250. };
  50251. var path3D;
  50252. var pathArray;
  50253. if (instance) {
  50254. path3D = (instance.path3D).update(curve);
  50255. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  50256. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  50257. return instance;
  50258. }
  50259. // extruded shape creation
  50260. path3D = new BABYLON.Path3D(curve);
  50261. var newShapePaths = new Array();
  50262. cap = (cap < 0 || cap > 3) ? 0 : cap;
  50263. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  50264. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  50265. extrudedGeneric.pathArray = pathArray;
  50266. extrudedGeneric.path3D = path3D;
  50267. extrudedGeneric.cap = cap;
  50268. return extrudedGeneric;
  50269. };
  50270. return MeshBuilder;
  50271. }());
  50272. BABYLON.MeshBuilder = MeshBuilder;
  50273. })(BABYLON || (BABYLON = {}));
  50274. //# sourceMappingURL=babylon.meshBuilder.js.map
  50275. var BABYLON;
  50276. (function (BABYLON) {
  50277. var AudioEngine = /** @class */ (function () {
  50278. function AudioEngine() {
  50279. this._audioContext = null;
  50280. this._audioContextInitialized = false;
  50281. this.canUseWebAudio = false;
  50282. this.WarnedWebAudioUnsupported = false;
  50283. this.unlocked = false;
  50284. this.isMP3supported = false;
  50285. this.isOGGsupported = false;
  50286. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  50287. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  50288. this.canUseWebAudio = true;
  50289. }
  50290. var audioElem = document.createElement('audio');
  50291. try {
  50292. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  50293. this.isMP3supported = true;
  50294. }
  50295. }
  50296. catch (e) {
  50297. // protect error during capability check.
  50298. }
  50299. try {
  50300. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  50301. this.isOGGsupported = true;
  50302. }
  50303. }
  50304. catch (e) {
  50305. // protect error during capability check.
  50306. }
  50307. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  50308. this._unlockiOSaudio();
  50309. }
  50310. else {
  50311. this.unlocked = true;
  50312. }
  50313. }
  50314. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  50315. get: function () {
  50316. if (!this._audioContextInitialized) {
  50317. this._initializeAudioContext();
  50318. }
  50319. return this._audioContext;
  50320. },
  50321. enumerable: true,
  50322. configurable: true
  50323. });
  50324. AudioEngine.prototype._unlockiOSaudio = function () {
  50325. var _this = this;
  50326. var unlockaudio = function () {
  50327. if (!_this.audioContext) {
  50328. return;
  50329. }
  50330. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  50331. var source = _this.audioContext.createBufferSource();
  50332. source.buffer = buffer;
  50333. source.connect(_this.audioContext.destination);
  50334. source.start(0);
  50335. setTimeout(function () {
  50336. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  50337. _this.unlocked = true;
  50338. window.removeEventListener('touchend', unlockaudio, false);
  50339. if (_this.onAudioUnlocked) {
  50340. _this.onAudioUnlocked();
  50341. }
  50342. }
  50343. }, 0);
  50344. };
  50345. window.addEventListener('touchend', unlockaudio, false);
  50346. };
  50347. AudioEngine.prototype._initializeAudioContext = function () {
  50348. try {
  50349. if (this.canUseWebAudio) {
  50350. this._audioContext = new AudioContext();
  50351. // create a global volume gain node
  50352. this.masterGain = this._audioContext.createGain();
  50353. this.masterGain.gain.value = 1;
  50354. this.masterGain.connect(this._audioContext.destination);
  50355. this._audioContextInitialized = true;
  50356. }
  50357. }
  50358. catch (e) {
  50359. this.canUseWebAudio = false;
  50360. BABYLON.Tools.Error("Web Audio: " + e.message);
  50361. }
  50362. };
  50363. AudioEngine.prototype.dispose = function () {
  50364. if (this.canUseWebAudio && this._audioContextInitialized) {
  50365. if (this._connectedAnalyser && this._audioContext) {
  50366. this._connectedAnalyser.stopDebugCanvas();
  50367. this._connectedAnalyser.dispose();
  50368. this.masterGain.disconnect();
  50369. this.masterGain.connect(this._audioContext.destination);
  50370. this._connectedAnalyser = null;
  50371. }
  50372. this.masterGain.gain.value = 1;
  50373. }
  50374. this.WarnedWebAudioUnsupported = false;
  50375. };
  50376. AudioEngine.prototype.getGlobalVolume = function () {
  50377. if (this.canUseWebAudio && this._audioContextInitialized) {
  50378. return this.masterGain.gain.value;
  50379. }
  50380. else {
  50381. return -1;
  50382. }
  50383. };
  50384. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  50385. if (this.canUseWebAudio && this._audioContextInitialized) {
  50386. this.masterGain.gain.value = newVolume;
  50387. }
  50388. };
  50389. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  50390. if (this._connectedAnalyser) {
  50391. this._connectedAnalyser.stopDebugCanvas();
  50392. }
  50393. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  50394. this._connectedAnalyser = analyser;
  50395. this.masterGain.disconnect();
  50396. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  50397. }
  50398. };
  50399. return AudioEngine;
  50400. }());
  50401. BABYLON.AudioEngine = AudioEngine;
  50402. })(BABYLON || (BABYLON = {}));
  50403. //# sourceMappingURL=babylon.audioEngine.js.map
  50404. var BABYLON;
  50405. (function (BABYLON) {
  50406. var Sound = /** @class */ (function () {
  50407. /**
  50408. * Create a sound and attach it to a scene
  50409. * @param name Name of your sound
  50410. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  50411. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  50412. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  50413. */
  50414. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  50415. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  50416. var _this = this;
  50417. this.autoplay = false;
  50418. this.loop = false;
  50419. this.useCustomAttenuation = false;
  50420. this.spatialSound = false;
  50421. this.refDistance = 1;
  50422. this.rolloffFactor = 1;
  50423. this.maxDistance = 100;
  50424. this.distanceModel = "linear";
  50425. this._panningModel = "equalpower";
  50426. this._playbackRate = 1;
  50427. this._streaming = false;
  50428. this._startTime = 0;
  50429. this._startOffset = 0;
  50430. this._position = BABYLON.Vector3.Zero();
  50431. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  50432. this._volume = 1;
  50433. this._isReadyToPlay = false;
  50434. this.isPlaying = false;
  50435. this.isPaused = false;
  50436. this._isDirectional = false;
  50437. // Used if you'd like to create a directional sound.
  50438. // If not set, the sound will be omnidirectional
  50439. this._coneInnerAngle = 360;
  50440. this._coneOuterAngle = 360;
  50441. this._coneOuterGain = 0;
  50442. this._isOutputConnected = false;
  50443. this._urlType = "Unknown";
  50444. this.name = name;
  50445. this._scene = scene;
  50446. this._readyToPlayCallback = readyToPlayCallback;
  50447. // Default custom attenuation function is a linear attenuation
  50448. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  50449. if (currentDistance < maxDistance) {
  50450. return currentVolume * (1 - currentDistance / maxDistance);
  50451. }
  50452. else {
  50453. return 0;
  50454. }
  50455. };
  50456. if (options) {
  50457. this.autoplay = options.autoplay || false;
  50458. this.loop = options.loop || false;
  50459. // if volume === 0, we need another way to check this option
  50460. if (options.volume !== undefined) {
  50461. this._volume = options.volume;
  50462. }
  50463. this.spatialSound = options.spatialSound || false;
  50464. this.maxDistance = options.maxDistance || 100;
  50465. this.useCustomAttenuation = options.useCustomAttenuation || false;
  50466. this.rolloffFactor = options.rolloffFactor || 1;
  50467. this.refDistance = options.refDistance || 1;
  50468. this.distanceModel = options.distanceModel || "linear";
  50469. this._playbackRate = options.playbackRate || 1;
  50470. this._streaming = options.streaming || false;
  50471. }
  50472. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  50473. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  50474. this._soundGain.gain.value = this._volume;
  50475. this._inputAudioNode = this._soundGain;
  50476. this._ouputAudioNode = this._soundGain;
  50477. if (this.spatialSound) {
  50478. this._createSpatialParameters();
  50479. }
  50480. this._scene.mainSoundTrack.AddSound(this);
  50481. var validParameter = true;
  50482. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  50483. if (urlOrArrayBuffer) {
  50484. if (typeof (urlOrArrayBuffer) === "string")
  50485. this._urlType = "String";
  50486. if (Array.isArray(urlOrArrayBuffer))
  50487. this._urlType = "Array";
  50488. if (urlOrArrayBuffer instanceof ArrayBuffer)
  50489. this._urlType = "ArrayBuffer";
  50490. var urls = [];
  50491. var codecSupportedFound = false;
  50492. switch (this._urlType) {
  50493. case "ArrayBuffer":
  50494. if (urlOrArrayBuffer.byteLength > 0) {
  50495. codecSupportedFound = true;
  50496. this._soundLoaded(urlOrArrayBuffer);
  50497. }
  50498. break;
  50499. case "String":
  50500. urls.push(urlOrArrayBuffer);
  50501. case "Array":
  50502. if (urls.length === 0)
  50503. urls = urlOrArrayBuffer;
  50504. // If we found a supported format, we load it immediately and stop the loop
  50505. for (var i = 0; i < urls.length; i++) {
  50506. var url = urls[i];
  50507. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  50508. codecSupportedFound = true;
  50509. }
  50510. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  50511. codecSupportedFound = true;
  50512. }
  50513. if (url.indexOf(".wav", url.length - 4) !== -1) {
  50514. codecSupportedFound = true;
  50515. }
  50516. if (url.indexOf("blob:") !== -1) {
  50517. codecSupportedFound = true;
  50518. }
  50519. if (codecSupportedFound) {
  50520. // Loading sound using XHR2
  50521. if (!this._streaming) {
  50522. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  50523. }
  50524. else {
  50525. this._htmlAudioElement = new Audio(url);
  50526. this._htmlAudioElement.controls = false;
  50527. this._htmlAudioElement.loop = this.loop;
  50528. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  50529. this._htmlAudioElement.preload = "auto";
  50530. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  50531. _this._isReadyToPlay = true;
  50532. if (_this.autoplay) {
  50533. _this.play();
  50534. }
  50535. if (_this._readyToPlayCallback) {
  50536. _this._readyToPlayCallback();
  50537. }
  50538. });
  50539. document.body.appendChild(this._htmlAudioElement);
  50540. }
  50541. break;
  50542. }
  50543. }
  50544. break;
  50545. default:
  50546. validParameter = false;
  50547. break;
  50548. }
  50549. if (!validParameter) {
  50550. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  50551. }
  50552. else {
  50553. if (!codecSupportedFound) {
  50554. this._isReadyToPlay = true;
  50555. // Simulating a ready to play event to avoid breaking code path
  50556. if (this._readyToPlayCallback) {
  50557. window.setTimeout(function () {
  50558. if (_this._readyToPlayCallback) {
  50559. _this._readyToPlayCallback();
  50560. }
  50561. }, 1000);
  50562. }
  50563. }
  50564. }
  50565. }
  50566. }
  50567. else {
  50568. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  50569. this._scene.mainSoundTrack.AddSound(this);
  50570. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  50571. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  50572. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  50573. }
  50574. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  50575. if (this._readyToPlayCallback) {
  50576. window.setTimeout(function () {
  50577. if (_this._readyToPlayCallback) {
  50578. _this._readyToPlayCallback();
  50579. }
  50580. }, 1000);
  50581. }
  50582. }
  50583. }
  50584. Sound.prototype.dispose = function () {
  50585. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  50586. if (this.isPlaying) {
  50587. this.stop();
  50588. }
  50589. this._isReadyToPlay = false;
  50590. if (this.soundTrackId === -1) {
  50591. this._scene.mainSoundTrack.RemoveSound(this);
  50592. }
  50593. else {
  50594. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  50595. }
  50596. if (this._soundGain) {
  50597. this._soundGain.disconnect();
  50598. this._soundGain = null;
  50599. }
  50600. if (this._soundPanner) {
  50601. this._soundPanner.disconnect();
  50602. this._soundPanner = null;
  50603. }
  50604. if (this._soundSource) {
  50605. this._soundSource.disconnect();
  50606. this._soundSource = null;
  50607. }
  50608. this._audioBuffer = null;
  50609. if (this._htmlAudioElement) {
  50610. this._htmlAudioElement.pause();
  50611. this._htmlAudioElement.src = "";
  50612. document.body.removeChild(this._htmlAudioElement);
  50613. }
  50614. if (this._connectedMesh && this._registerFunc) {
  50615. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  50616. this._connectedMesh = null;
  50617. }
  50618. }
  50619. };
  50620. Sound.prototype.isReady = function () {
  50621. return this._isReadyToPlay;
  50622. };
  50623. Sound.prototype._soundLoaded = function (audioData) {
  50624. var _this = this;
  50625. if (!BABYLON.Engine.audioEngine.audioContext) {
  50626. return;
  50627. }
  50628. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  50629. _this._audioBuffer = buffer;
  50630. _this._isReadyToPlay = true;
  50631. if (_this.autoplay) {
  50632. _this.play();
  50633. }
  50634. if (_this._readyToPlayCallback) {
  50635. _this._readyToPlayCallback();
  50636. }
  50637. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  50638. };
  50639. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  50640. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  50641. this._audioBuffer = audioBuffer;
  50642. this._isReadyToPlay = true;
  50643. }
  50644. };
  50645. Sound.prototype.updateOptions = function (options) {
  50646. if (options) {
  50647. this.loop = options.loop || this.loop;
  50648. this.maxDistance = options.maxDistance || this.maxDistance;
  50649. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  50650. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  50651. this.refDistance = options.refDistance || this.refDistance;
  50652. this.distanceModel = options.distanceModel || this.distanceModel;
  50653. this._playbackRate = options.playbackRate || this._playbackRate;
  50654. this._updateSpatialParameters();
  50655. if (this.isPlaying) {
  50656. if (this._streaming) {
  50657. this._htmlAudioElement.playbackRate = this._playbackRate;
  50658. }
  50659. else {
  50660. if (this._soundSource) {
  50661. this._soundSource.playbackRate.value = this._playbackRate;
  50662. }
  50663. }
  50664. }
  50665. }
  50666. };
  50667. Sound.prototype._createSpatialParameters = function () {
  50668. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  50669. if (this._scene.headphone) {
  50670. this._panningModel = "HRTF";
  50671. }
  50672. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  50673. this._updateSpatialParameters();
  50674. this._soundPanner.connect(this._ouputAudioNode);
  50675. this._inputAudioNode = this._soundPanner;
  50676. }
  50677. };
  50678. Sound.prototype._updateSpatialParameters = function () {
  50679. if (this.spatialSound && this._soundPanner) {
  50680. if (this.useCustomAttenuation) {
  50681. // Tricks to disable in a way embedded Web Audio attenuation
  50682. this._soundPanner.distanceModel = "linear";
  50683. this._soundPanner.maxDistance = Number.MAX_VALUE;
  50684. this._soundPanner.refDistance = 1;
  50685. this._soundPanner.rolloffFactor = 1;
  50686. this._soundPanner.panningModel = this._panningModel;
  50687. }
  50688. else {
  50689. this._soundPanner.distanceModel = this.distanceModel;
  50690. this._soundPanner.maxDistance = this.maxDistance;
  50691. this._soundPanner.refDistance = this.refDistance;
  50692. this._soundPanner.rolloffFactor = this.rolloffFactor;
  50693. this._soundPanner.panningModel = this._panningModel;
  50694. }
  50695. }
  50696. };
  50697. Sound.prototype.switchPanningModelToHRTF = function () {
  50698. this._panningModel = "HRTF";
  50699. this._switchPanningModel();
  50700. };
  50701. Sound.prototype.switchPanningModelToEqualPower = function () {
  50702. this._panningModel = "equalpower";
  50703. this._switchPanningModel();
  50704. };
  50705. Sound.prototype._switchPanningModel = function () {
  50706. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  50707. this._soundPanner.panningModel = this._panningModel;
  50708. }
  50709. };
  50710. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  50711. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  50712. if (this._isOutputConnected) {
  50713. this._ouputAudioNode.disconnect();
  50714. }
  50715. this._ouputAudioNode.connect(soundTrackAudioNode);
  50716. this._isOutputConnected = true;
  50717. }
  50718. };
  50719. /**
  50720. * Transform this sound into a directional source
  50721. * @param coneInnerAngle Size of the inner cone in degree
  50722. * @param coneOuterAngle Size of the outer cone in degree
  50723. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  50724. */
  50725. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  50726. if (coneOuterAngle < coneInnerAngle) {
  50727. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  50728. return;
  50729. }
  50730. this._coneInnerAngle = coneInnerAngle;
  50731. this._coneOuterAngle = coneOuterAngle;
  50732. this._coneOuterGain = coneOuterGain;
  50733. this._isDirectional = true;
  50734. if (this.isPlaying && this.loop) {
  50735. this.stop();
  50736. this.play();
  50737. }
  50738. };
  50739. Sound.prototype.setPosition = function (newPosition) {
  50740. this._position = newPosition;
  50741. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  50742. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  50743. }
  50744. };
  50745. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  50746. this._localDirection = newLocalDirection;
  50747. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  50748. this._updateDirection();
  50749. }
  50750. };
  50751. Sound.prototype._updateDirection = function () {
  50752. if (!this._connectedMesh || !this._soundPanner) {
  50753. return;
  50754. }
  50755. var mat = this._connectedMesh.getWorldMatrix();
  50756. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  50757. direction.normalize();
  50758. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  50759. };
  50760. Sound.prototype.updateDistanceFromListener = function () {
  50761. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  50762. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  50763. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  50764. }
  50765. };
  50766. Sound.prototype.setAttenuationFunction = function (callback) {
  50767. this._customAttenuationFunction = callback;
  50768. };
  50769. /**
  50770. * Play the sound
  50771. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  50772. * @param offset (optional) Start the sound setting it at a specific time
  50773. */
  50774. Sound.prototype.play = function (time, offset) {
  50775. var _this = this;
  50776. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  50777. try {
  50778. if (this._startOffset < 0) {
  50779. time = -this._startOffset;
  50780. this._startOffset = 0;
  50781. }
  50782. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  50783. if (!this._soundSource || !this._streamingSource) {
  50784. if (this.spatialSound && this._soundPanner) {
  50785. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  50786. if (this._isDirectional) {
  50787. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  50788. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  50789. this._soundPanner.coneOuterGain = this._coneOuterGain;
  50790. if (this._connectedMesh) {
  50791. this._updateDirection();
  50792. }
  50793. else {
  50794. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  50795. }
  50796. }
  50797. }
  50798. }
  50799. if (this._streaming) {
  50800. if (!this._streamingSource) {
  50801. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  50802. this._htmlAudioElement.onended = function () { _this._onended(); };
  50803. this._htmlAudioElement.playbackRate = this._playbackRate;
  50804. }
  50805. this._streamingSource.disconnect();
  50806. this._streamingSource.connect(this._inputAudioNode);
  50807. this._htmlAudioElement.play();
  50808. }
  50809. else {
  50810. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  50811. this._soundSource.buffer = this._audioBuffer;
  50812. this._soundSource.connect(this._inputAudioNode);
  50813. this._soundSource.loop = this.loop;
  50814. this._soundSource.playbackRate.value = this._playbackRate;
  50815. this._soundSource.onended = function () { _this._onended(); };
  50816. if (this._soundSource.buffer) {
  50817. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  50818. }
  50819. }
  50820. this._startTime = startTime;
  50821. this.isPlaying = true;
  50822. this.isPaused = false;
  50823. }
  50824. catch (ex) {
  50825. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  50826. }
  50827. }
  50828. };
  50829. Sound.prototype._onended = function () {
  50830. this.isPlaying = false;
  50831. if (this.onended) {
  50832. this.onended();
  50833. }
  50834. };
  50835. /**
  50836. * Stop the sound
  50837. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  50838. */
  50839. Sound.prototype.stop = function (time) {
  50840. if (this.isPlaying) {
  50841. if (this._streaming) {
  50842. this._htmlAudioElement.pause();
  50843. // Test needed for Firefox or it will generate an Invalid State Error
  50844. if (this._htmlAudioElement.currentTime > 0) {
  50845. this._htmlAudioElement.currentTime = 0;
  50846. }
  50847. }
  50848. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  50849. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  50850. this._soundSource.stop(stopTime);
  50851. this._soundSource.onended = function () { };
  50852. if (!this.isPaused) {
  50853. this._startOffset = 0;
  50854. }
  50855. }
  50856. this.isPlaying = false;
  50857. }
  50858. };
  50859. Sound.prototype.pause = function () {
  50860. if (this.isPlaying) {
  50861. this.isPaused = true;
  50862. if (this._streaming) {
  50863. this._htmlAudioElement.pause();
  50864. }
  50865. else if (BABYLON.Engine.audioEngine.audioContext) {
  50866. this.stop(0);
  50867. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  50868. }
  50869. }
  50870. };
  50871. Sound.prototype.setVolume = function (newVolume, time) {
  50872. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  50873. if (time && BABYLON.Engine.audioEngine.audioContext) {
  50874. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  50875. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  50876. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  50877. }
  50878. else {
  50879. this._soundGain.gain.value = newVolume;
  50880. }
  50881. }
  50882. this._volume = newVolume;
  50883. };
  50884. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  50885. this._playbackRate = newPlaybackRate;
  50886. if (this.isPlaying) {
  50887. if (this._streaming) {
  50888. this._htmlAudioElement.playbackRate = this._playbackRate;
  50889. }
  50890. else if (this._soundSource) {
  50891. this._soundSource.playbackRate.value = this._playbackRate;
  50892. }
  50893. }
  50894. };
  50895. Sound.prototype.getVolume = function () {
  50896. return this._volume;
  50897. };
  50898. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  50899. var _this = this;
  50900. if (this._connectedMesh && this._registerFunc) {
  50901. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  50902. this._registerFunc = null;
  50903. }
  50904. this._connectedMesh = meshToConnectTo;
  50905. if (!this.spatialSound) {
  50906. this.spatialSound = true;
  50907. this._createSpatialParameters();
  50908. if (this.isPlaying && this.loop) {
  50909. this.stop();
  50910. this.play();
  50911. }
  50912. }
  50913. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  50914. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  50915. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  50916. };
  50917. Sound.prototype.detachFromMesh = function () {
  50918. if (this._connectedMesh && this._registerFunc) {
  50919. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  50920. this._registerFunc = null;
  50921. this._connectedMesh = null;
  50922. }
  50923. };
  50924. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  50925. if (!node.getBoundingInfo) {
  50926. return;
  50927. }
  50928. var mesh = node;
  50929. var boundingInfo = mesh.getBoundingInfo();
  50930. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  50931. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  50932. this._updateDirection();
  50933. }
  50934. };
  50935. Sound.prototype.clone = function () {
  50936. var _this = this;
  50937. if (!this._streaming) {
  50938. var setBufferAndRun = function () {
  50939. if (_this._isReadyToPlay) {
  50940. clonedSound._audioBuffer = _this.getAudioBuffer();
  50941. clonedSound._isReadyToPlay = true;
  50942. if (clonedSound.autoplay) {
  50943. clonedSound.play();
  50944. }
  50945. }
  50946. else {
  50947. window.setTimeout(setBufferAndRun, 300);
  50948. }
  50949. };
  50950. var currentOptions = {
  50951. autoplay: this.autoplay, loop: this.loop,
  50952. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  50953. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  50954. refDistance: this.refDistance, distanceModel: this.distanceModel
  50955. };
  50956. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  50957. if (this.useCustomAttenuation) {
  50958. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  50959. }
  50960. clonedSound.setPosition(this._position);
  50961. clonedSound.setPlaybackRate(this._playbackRate);
  50962. setBufferAndRun();
  50963. return clonedSound;
  50964. }
  50965. else {
  50966. return null;
  50967. }
  50968. };
  50969. Sound.prototype.getAudioBuffer = function () {
  50970. return this._audioBuffer;
  50971. };
  50972. Sound.prototype.serialize = function () {
  50973. var serializationObject = {
  50974. name: this.name,
  50975. url: this.name,
  50976. autoplay: this.autoplay,
  50977. loop: this.loop,
  50978. volume: this._volume,
  50979. spatialSound: this.spatialSound,
  50980. maxDistance: this.maxDistance,
  50981. rolloffFactor: this.rolloffFactor,
  50982. refDistance: this.refDistance,
  50983. distanceModel: this.distanceModel,
  50984. playbackRate: this._playbackRate,
  50985. panningModel: this._panningModel,
  50986. soundTrackId: this.soundTrackId
  50987. };
  50988. if (this.spatialSound) {
  50989. if (this._connectedMesh)
  50990. serializationObject.connectedMeshId = this._connectedMesh.id;
  50991. serializationObject.position = this._position.asArray();
  50992. serializationObject.refDistance = this.refDistance;
  50993. serializationObject.distanceModel = this.distanceModel;
  50994. serializationObject.isDirectional = this._isDirectional;
  50995. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  50996. serializationObject.coneInnerAngle = this._coneInnerAngle;
  50997. serializationObject.coneOuterAngle = this._coneOuterAngle;
  50998. serializationObject.coneOuterGain = this._coneOuterGain;
  50999. }
  51000. return serializationObject;
  51001. };
  51002. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  51003. var soundName = parsedSound.name;
  51004. var soundUrl;
  51005. if (parsedSound.url) {
  51006. soundUrl = rootUrl + parsedSound.url;
  51007. }
  51008. else {
  51009. soundUrl = rootUrl + soundName;
  51010. }
  51011. var options = {
  51012. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  51013. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  51014. rolloffFactor: parsedSound.rolloffFactor,
  51015. refDistance: parsedSound.refDistance,
  51016. distanceModel: parsedSound.distanceModel,
  51017. playbackRate: parsedSound.playbackRate
  51018. };
  51019. var newSound;
  51020. if (!sourceSound) {
  51021. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  51022. scene._addPendingData(newSound);
  51023. }
  51024. else {
  51025. var setBufferAndRun = function () {
  51026. if (sourceSound._isReadyToPlay) {
  51027. newSound._audioBuffer = sourceSound.getAudioBuffer();
  51028. newSound._isReadyToPlay = true;
  51029. if (newSound.autoplay) {
  51030. newSound.play();
  51031. }
  51032. }
  51033. else {
  51034. window.setTimeout(setBufferAndRun, 300);
  51035. }
  51036. };
  51037. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  51038. setBufferAndRun();
  51039. }
  51040. if (parsedSound.position) {
  51041. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  51042. newSound.setPosition(soundPosition);
  51043. }
  51044. if (parsedSound.isDirectional) {
  51045. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  51046. if (parsedSound.localDirectionToMesh) {
  51047. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  51048. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  51049. }
  51050. }
  51051. if (parsedSound.connectedMeshId) {
  51052. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  51053. if (connectedMesh) {
  51054. newSound.attachToMesh(connectedMesh);
  51055. }
  51056. }
  51057. return newSound;
  51058. };
  51059. return Sound;
  51060. }());
  51061. BABYLON.Sound = Sound;
  51062. })(BABYLON || (BABYLON = {}));
  51063. //# sourceMappingURL=babylon.sound.js.map
  51064. var BABYLON;
  51065. (function (BABYLON) {
  51066. var SoundTrack = /** @class */ (function () {
  51067. function SoundTrack(scene, options) {
  51068. this.id = -1;
  51069. this._isMainTrack = false;
  51070. this._isInitialized = false;
  51071. this._scene = scene;
  51072. this.soundCollection = new Array();
  51073. this._options = options;
  51074. if (!this._isMainTrack) {
  51075. this._scene.soundTracks.push(this);
  51076. this.id = this._scene.soundTracks.length - 1;
  51077. }
  51078. }
  51079. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  51080. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  51081. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  51082. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  51083. if (this._options) {
  51084. if (this._options.volume) {
  51085. this._outputAudioNode.gain.value = this._options.volume;
  51086. }
  51087. if (this._options.mainTrack) {
  51088. this._isMainTrack = this._options.mainTrack;
  51089. }
  51090. }
  51091. this._isInitialized = true;
  51092. }
  51093. };
  51094. SoundTrack.prototype.dispose = function () {
  51095. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  51096. if (this._connectedAnalyser) {
  51097. this._connectedAnalyser.stopDebugCanvas();
  51098. }
  51099. while (this.soundCollection.length) {
  51100. this.soundCollection[0].dispose();
  51101. }
  51102. if (this._outputAudioNode) {
  51103. this._outputAudioNode.disconnect();
  51104. }
  51105. this._outputAudioNode = null;
  51106. }
  51107. };
  51108. SoundTrack.prototype.AddSound = function (sound) {
  51109. if (!this._isInitialized) {
  51110. this._initializeSoundTrackAudioGraph();
  51111. }
  51112. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  51113. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  51114. }
  51115. if (sound.soundTrackId) {
  51116. if (sound.soundTrackId === -1) {
  51117. this._scene.mainSoundTrack.RemoveSound(sound);
  51118. }
  51119. else {
  51120. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  51121. }
  51122. }
  51123. this.soundCollection.push(sound);
  51124. sound.soundTrackId = this.id;
  51125. };
  51126. SoundTrack.prototype.RemoveSound = function (sound) {
  51127. var index = this.soundCollection.indexOf(sound);
  51128. if (index !== -1) {
  51129. this.soundCollection.splice(index, 1);
  51130. }
  51131. };
  51132. SoundTrack.prototype.setVolume = function (newVolume) {
  51133. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  51134. this._outputAudioNode.gain.value = newVolume;
  51135. }
  51136. };
  51137. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  51138. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  51139. for (var i = 0; i < this.soundCollection.length; i++) {
  51140. this.soundCollection[i].switchPanningModelToHRTF();
  51141. }
  51142. }
  51143. };
  51144. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  51145. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  51146. for (var i = 0; i < this.soundCollection.length; i++) {
  51147. this.soundCollection[i].switchPanningModelToEqualPower();
  51148. }
  51149. }
  51150. };
  51151. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  51152. if (this._connectedAnalyser) {
  51153. this._connectedAnalyser.stopDebugCanvas();
  51154. }
  51155. this._connectedAnalyser = analyser;
  51156. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  51157. this._outputAudioNode.disconnect();
  51158. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  51159. }
  51160. };
  51161. return SoundTrack;
  51162. }());
  51163. BABYLON.SoundTrack = SoundTrack;
  51164. })(BABYLON || (BABYLON = {}));
  51165. //# sourceMappingURL=babylon.soundtrack.js.map
  51166. var BABYLON;
  51167. (function (BABYLON) {
  51168. var Analyser = /** @class */ (function () {
  51169. function Analyser(scene) {
  51170. this.SMOOTHING = 0.75;
  51171. this.FFT_SIZE = 512;
  51172. this.BARGRAPHAMPLITUDE = 256;
  51173. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  51174. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  51175. this._scene = scene;
  51176. this._audioEngine = BABYLON.Engine.audioEngine;
  51177. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  51178. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  51179. this._webAudioAnalyser.minDecibels = -140;
  51180. this._webAudioAnalyser.maxDecibels = 0;
  51181. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  51182. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  51183. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  51184. }
  51185. }
  51186. Analyser.prototype.getFrequencyBinCount = function () {
  51187. if (this._audioEngine.canUseWebAudio) {
  51188. return this._webAudioAnalyser.frequencyBinCount;
  51189. }
  51190. else {
  51191. return 0;
  51192. }
  51193. };
  51194. Analyser.prototype.getByteFrequencyData = function () {
  51195. if (this._audioEngine.canUseWebAudio) {
  51196. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  51197. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  51198. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  51199. }
  51200. return this._byteFreqs;
  51201. };
  51202. Analyser.prototype.getByteTimeDomainData = function () {
  51203. if (this._audioEngine.canUseWebAudio) {
  51204. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  51205. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  51206. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  51207. }
  51208. return this._byteTime;
  51209. };
  51210. Analyser.prototype.getFloatFrequencyData = function () {
  51211. if (this._audioEngine.canUseWebAudio) {
  51212. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  51213. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  51214. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  51215. }
  51216. return this._floatFreqs;
  51217. };
  51218. Analyser.prototype.drawDebugCanvas = function () {
  51219. var _this = this;
  51220. if (this._audioEngine.canUseWebAudio) {
  51221. if (!this._debugCanvas) {
  51222. this._debugCanvas = document.createElement("canvas");
  51223. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  51224. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  51225. this._debugCanvas.style.position = "absolute";
  51226. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  51227. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  51228. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  51229. document.body.appendChild(this._debugCanvas);
  51230. this._registerFunc = function () {
  51231. _this.drawDebugCanvas();
  51232. };
  51233. this._scene.registerBeforeRender(this._registerFunc);
  51234. }
  51235. if (this._registerFunc && this._debugCanvasContext) {
  51236. var workingArray = this.getByteFrequencyData();
  51237. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  51238. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  51239. // Draw the frequency domain chart.
  51240. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  51241. var value = workingArray[i];
  51242. var percent = value / this.BARGRAPHAMPLITUDE;
  51243. var height = this.DEBUGCANVASSIZE.height * percent;
  51244. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  51245. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  51246. var hue = i / this.getFrequencyBinCount() * 360;
  51247. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  51248. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  51249. }
  51250. }
  51251. }
  51252. };
  51253. Analyser.prototype.stopDebugCanvas = function () {
  51254. if (this._debugCanvas) {
  51255. if (this._registerFunc) {
  51256. this._scene.unregisterBeforeRender(this._registerFunc);
  51257. this._registerFunc = null;
  51258. }
  51259. document.body.removeChild(this._debugCanvas);
  51260. this._debugCanvas = null;
  51261. this._debugCanvasContext = null;
  51262. }
  51263. };
  51264. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  51265. if (this._audioEngine.canUseWebAudio) {
  51266. inputAudioNode.connect(this._webAudioAnalyser);
  51267. this._webAudioAnalyser.connect(outputAudioNode);
  51268. }
  51269. };
  51270. Analyser.prototype.dispose = function () {
  51271. if (this._audioEngine.canUseWebAudio) {
  51272. this._webAudioAnalyser.disconnect();
  51273. }
  51274. };
  51275. return Analyser;
  51276. }());
  51277. BABYLON.Analyser = Analyser;
  51278. })(BABYLON || (BABYLON = {}));
  51279. //# sourceMappingURL=babylon.analyser.js.map
  51280. var BABYLON;
  51281. (function (BABYLON) {
  51282. var CubeTexture = /** @class */ (function (_super) {
  51283. __extends(CubeTexture, _super);
  51284. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  51285. if (extensions === void 0) { extensions = null; }
  51286. if (noMipmap === void 0) { noMipmap = false; }
  51287. if (files === void 0) { files = null; }
  51288. if (onLoad === void 0) { onLoad = null; }
  51289. if (onError === void 0) { onError = null; }
  51290. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  51291. if (prefiltered === void 0) { prefiltered = false; }
  51292. if (forcedExtension === void 0) { forcedExtension = null; }
  51293. var _this = _super.call(this, scene) || this;
  51294. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  51295. _this.name = rootUrl;
  51296. _this.url = rootUrl;
  51297. _this._noMipmap = noMipmap;
  51298. _this.hasAlpha = false;
  51299. _this._format = format;
  51300. _this._prefiltered = prefiltered;
  51301. _this.isCube = true;
  51302. _this._textureMatrix = BABYLON.Matrix.Identity();
  51303. if (prefiltered) {
  51304. _this.gammaSpace = false;
  51305. }
  51306. if (!rootUrl && !files) {
  51307. return _this;
  51308. }
  51309. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  51310. var lastDot = rootUrl.lastIndexOf(".");
  51311. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  51312. var isDDS = (extension === ".dds");
  51313. if (!files) {
  51314. if (!isDDS && !extensions) {
  51315. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  51316. }
  51317. files = [];
  51318. if (extensions) {
  51319. for (var index = 0; index < extensions.length; index++) {
  51320. files.push(rootUrl + extensions[index]);
  51321. }
  51322. }
  51323. }
  51324. _this._files = files;
  51325. if (!_this._texture) {
  51326. if (!scene.useDelayedTextureLoading) {
  51327. if (prefiltered) {
  51328. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  51329. }
  51330. else {
  51331. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  51332. }
  51333. }
  51334. else {
  51335. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  51336. }
  51337. }
  51338. else if (onLoad) {
  51339. if (_this._texture.isReady) {
  51340. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  51341. }
  51342. else {
  51343. _this._texture.onLoadedObservable.add(onLoad);
  51344. }
  51345. }
  51346. return _this;
  51347. }
  51348. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  51349. return new CubeTexture("", scene, null, noMipmap, files);
  51350. };
  51351. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  51352. if (forcedExtension === void 0) { forcedExtension = null; }
  51353. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  51354. };
  51355. // Methods
  51356. CubeTexture.prototype.delayLoad = function () {
  51357. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  51358. return;
  51359. }
  51360. var scene = this.getScene();
  51361. if (!scene) {
  51362. return;
  51363. }
  51364. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  51365. this._texture = this._getFromCache(this.url, this._noMipmap);
  51366. if (!this._texture) {
  51367. if (this._prefiltered) {
  51368. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  51369. }
  51370. else {
  51371. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  51372. }
  51373. }
  51374. };
  51375. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  51376. return this._textureMatrix;
  51377. };
  51378. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  51379. this._textureMatrix = value;
  51380. };
  51381. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  51382. var texture = BABYLON.SerializationHelper.Parse(function () {
  51383. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  51384. }, parsedTexture, scene);
  51385. // Animations
  51386. if (parsedTexture.animations) {
  51387. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  51388. var parsedAnimation = parsedTexture.animations[animationIndex];
  51389. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  51390. }
  51391. }
  51392. return texture;
  51393. };
  51394. CubeTexture.prototype.clone = function () {
  51395. var _this = this;
  51396. return BABYLON.SerializationHelper.Clone(function () {
  51397. var scene = _this.getScene();
  51398. if (!scene) {
  51399. return _this;
  51400. }
  51401. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  51402. }, this);
  51403. };
  51404. return CubeTexture;
  51405. }(BABYLON.BaseTexture));
  51406. BABYLON.CubeTexture = CubeTexture;
  51407. })(BABYLON || (BABYLON = {}));
  51408. //# sourceMappingURL=babylon.cubeTexture.js.map
  51409. var BABYLON;
  51410. (function (BABYLON) {
  51411. var RenderTargetTexture = /** @class */ (function (_super) {
  51412. __extends(RenderTargetTexture, _super);
  51413. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  51414. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  51415. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51416. if (isCube === void 0) { isCube = false; }
  51417. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51418. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  51419. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  51420. if (isMulti === void 0) { isMulti = false; }
  51421. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  51422. _this.isCube = isCube;
  51423. /**
  51424. * Use this list to define the list of mesh you want to render.
  51425. */
  51426. _this.renderList = new Array();
  51427. _this.renderParticles = true;
  51428. _this.renderSprites = false;
  51429. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  51430. _this.ignoreCameraViewport = false;
  51431. // Events
  51432. /**
  51433. * An event triggered when the texture is unbind.
  51434. * @type {BABYLON.Observable}
  51435. */
  51436. _this.onBeforeBindObservable = new BABYLON.Observable();
  51437. /**
  51438. * An event triggered when the texture is unbind.
  51439. * @type {BABYLON.Observable}
  51440. */
  51441. _this.onAfterUnbindObservable = new BABYLON.Observable();
  51442. /**
  51443. * An event triggered before rendering the texture
  51444. * @type {BABYLON.Observable}
  51445. */
  51446. _this.onBeforeRenderObservable = new BABYLON.Observable();
  51447. /**
  51448. * An event triggered after rendering the texture
  51449. * @type {BABYLON.Observable}
  51450. */
  51451. _this.onAfterRenderObservable = new BABYLON.Observable();
  51452. /**
  51453. * An event triggered after the texture clear
  51454. * @type {BABYLON.Observable}
  51455. */
  51456. _this.onClearObservable = new BABYLON.Observable();
  51457. _this._currentRefreshId = -1;
  51458. _this._refreshRate = 1;
  51459. _this._samples = 1;
  51460. scene = _this.getScene();
  51461. if (!scene) {
  51462. return _this;
  51463. }
  51464. _this._engine = scene.getEngine();
  51465. _this.name = name;
  51466. _this.isRenderTarget = true;
  51467. _this._initialSizeParameter = size;
  51468. _this._processSizeParameter(size);
  51469. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  51470. });
  51471. _this._generateMipMaps = generateMipMaps ? true : false;
  51472. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  51473. // Rendering groups
  51474. _this._renderingManager = new BABYLON.RenderingManager(scene);
  51475. if (isMulti) {
  51476. return _this;
  51477. }
  51478. _this._renderTargetOptions = {
  51479. generateMipMaps: generateMipMaps,
  51480. type: type,
  51481. samplingMode: samplingMode,
  51482. generateDepthBuffer: generateDepthBuffer,
  51483. generateStencilBuffer: generateStencilBuffer
  51484. };
  51485. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  51486. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51487. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51488. }
  51489. if (isCube) {
  51490. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  51491. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  51492. _this._textureMatrix = BABYLON.Matrix.Identity();
  51493. }
  51494. else {
  51495. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  51496. }
  51497. return _this;
  51498. }
  51499. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  51500. get: function () {
  51501. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  51502. },
  51503. enumerable: true,
  51504. configurable: true
  51505. });
  51506. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  51507. get: function () {
  51508. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  51509. },
  51510. enumerable: true,
  51511. configurable: true
  51512. });
  51513. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  51514. get: function () {
  51515. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  51516. },
  51517. enumerable: true,
  51518. configurable: true
  51519. });
  51520. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  51521. set: function (callback) {
  51522. if (this._onAfterUnbindObserver) {
  51523. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  51524. }
  51525. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  51526. },
  51527. enumerable: true,
  51528. configurable: true
  51529. });
  51530. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  51531. set: function (callback) {
  51532. if (this._onBeforeRenderObserver) {
  51533. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  51534. }
  51535. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  51536. },
  51537. enumerable: true,
  51538. configurable: true
  51539. });
  51540. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  51541. set: function (callback) {
  51542. if (this._onAfterRenderObserver) {
  51543. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  51544. }
  51545. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  51546. },
  51547. enumerable: true,
  51548. configurable: true
  51549. });
  51550. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  51551. set: function (callback) {
  51552. if (this._onClearObserver) {
  51553. this.onClearObservable.remove(this._onClearObserver);
  51554. }
  51555. this._onClearObserver = this.onClearObservable.add(callback);
  51556. },
  51557. enumerable: true,
  51558. configurable: true
  51559. });
  51560. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  51561. get: function () {
  51562. return this._renderTargetOptions;
  51563. },
  51564. enumerable: true,
  51565. configurable: true
  51566. });
  51567. RenderTargetTexture.prototype._onRatioRescale = function () {
  51568. if (this._sizeRatio) {
  51569. this.resize(this._initialSizeParameter);
  51570. }
  51571. };
  51572. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  51573. if (size.ratio) {
  51574. this._sizeRatio = size.ratio;
  51575. this._size = {
  51576. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  51577. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  51578. };
  51579. }
  51580. else {
  51581. this._size = size;
  51582. }
  51583. };
  51584. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  51585. get: function () {
  51586. return this._samples;
  51587. },
  51588. set: function (value) {
  51589. if (this._samples === value) {
  51590. return;
  51591. }
  51592. var scene = this.getScene();
  51593. if (!scene) {
  51594. return;
  51595. }
  51596. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  51597. },
  51598. enumerable: true,
  51599. configurable: true
  51600. });
  51601. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  51602. this._currentRefreshId = -1;
  51603. };
  51604. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  51605. get: function () {
  51606. return this._refreshRate;
  51607. },
  51608. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  51609. set: function (value) {
  51610. this._refreshRate = value;
  51611. this.resetRefreshCounter();
  51612. },
  51613. enumerable: true,
  51614. configurable: true
  51615. });
  51616. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  51617. if (!this._postProcessManager) {
  51618. var scene = this.getScene();
  51619. if (!scene) {
  51620. return;
  51621. }
  51622. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  51623. this._postProcesses = new Array();
  51624. }
  51625. this._postProcesses.push(postProcess);
  51626. this._postProcesses[0].autoClear = false;
  51627. };
  51628. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  51629. if (!this._postProcesses) {
  51630. return;
  51631. }
  51632. if (dispose) {
  51633. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  51634. var postProcess = _a[_i];
  51635. postProcess.dispose();
  51636. }
  51637. }
  51638. this._postProcesses = [];
  51639. };
  51640. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  51641. if (!this._postProcesses) {
  51642. return;
  51643. }
  51644. var index = this._postProcesses.indexOf(postProcess);
  51645. if (index === -1) {
  51646. return;
  51647. }
  51648. this._postProcesses.splice(index, 1);
  51649. if (this._postProcesses.length > 0) {
  51650. this._postProcesses[0].autoClear = false;
  51651. }
  51652. };
  51653. RenderTargetTexture.prototype._shouldRender = function () {
  51654. if (this._currentRefreshId === -1) {
  51655. this._currentRefreshId = 1;
  51656. return true;
  51657. }
  51658. if (this.refreshRate === this._currentRefreshId) {
  51659. this._currentRefreshId = 1;
  51660. return true;
  51661. }
  51662. this._currentRefreshId++;
  51663. return false;
  51664. };
  51665. RenderTargetTexture.prototype.getRenderSize = function () {
  51666. if (this._size.width) {
  51667. return this._size.width;
  51668. }
  51669. return this._size;
  51670. };
  51671. RenderTargetTexture.prototype.getRenderWidth = function () {
  51672. if (this._size.width) {
  51673. return this._size.width;
  51674. }
  51675. return this._size;
  51676. };
  51677. RenderTargetTexture.prototype.getRenderHeight = function () {
  51678. if (this._size.width) {
  51679. return this._size.height;
  51680. }
  51681. return this._size;
  51682. };
  51683. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  51684. get: function () {
  51685. return true;
  51686. },
  51687. enumerable: true,
  51688. configurable: true
  51689. });
  51690. RenderTargetTexture.prototype.scale = function (ratio) {
  51691. var newSize = this.getRenderSize() * ratio;
  51692. this.resize(newSize);
  51693. };
  51694. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  51695. if (this.isCube) {
  51696. return this._textureMatrix;
  51697. }
  51698. return _super.prototype.getReflectionTextureMatrix.call(this);
  51699. };
  51700. RenderTargetTexture.prototype.resize = function (size) {
  51701. this.releaseInternalTexture();
  51702. var scene = this.getScene();
  51703. if (!scene) {
  51704. return;
  51705. }
  51706. this._processSizeParameter(size);
  51707. if (this.isCube) {
  51708. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  51709. }
  51710. else {
  51711. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  51712. }
  51713. };
  51714. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  51715. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  51716. if (dumpForDebug === void 0) { dumpForDebug = false; }
  51717. var scene = this.getScene();
  51718. if (!scene) {
  51719. return;
  51720. }
  51721. var engine = scene.getEngine();
  51722. if (this.useCameraPostProcesses !== undefined) {
  51723. useCameraPostProcess = this.useCameraPostProcesses;
  51724. }
  51725. if (this._waitingRenderList) {
  51726. this.renderList = [];
  51727. for (var index = 0; index < this._waitingRenderList.length; index++) {
  51728. var id = this._waitingRenderList[index];
  51729. var mesh_1 = scene.getMeshByID(id);
  51730. if (mesh_1) {
  51731. this.renderList.push(mesh_1);
  51732. }
  51733. }
  51734. delete this._waitingRenderList;
  51735. }
  51736. // Is predicate defined?
  51737. if (this.renderListPredicate) {
  51738. if (this.renderList) {
  51739. this.renderList.splice(0); // Clear previous renderList
  51740. }
  51741. else {
  51742. this.renderList = [];
  51743. }
  51744. var scene = this.getScene();
  51745. if (!scene) {
  51746. return;
  51747. }
  51748. var sceneMeshes = scene.meshes;
  51749. for (var index = 0; index < sceneMeshes.length; index++) {
  51750. var mesh = sceneMeshes[index];
  51751. if (this.renderListPredicate(mesh)) {
  51752. this.renderList.push(mesh);
  51753. }
  51754. }
  51755. }
  51756. this.onBeforeBindObservable.notifyObservers(this);
  51757. // Set custom projection.
  51758. // Needs to be before binding to prevent changing the aspect ratio.
  51759. var camera;
  51760. if (this.activeCamera) {
  51761. camera = this.activeCamera;
  51762. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  51763. if (this.activeCamera !== scene.activeCamera) {
  51764. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  51765. }
  51766. }
  51767. else {
  51768. camera = scene.activeCamera;
  51769. if (camera) {
  51770. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  51771. }
  51772. }
  51773. // Prepare renderingManager
  51774. this._renderingManager.reset();
  51775. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  51776. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  51777. var sceneRenderId = scene.getRenderId();
  51778. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  51779. var mesh = currentRenderList[meshIndex];
  51780. if (mesh) {
  51781. if (!mesh.isReady()) {
  51782. // Reset _currentRefreshId
  51783. this.resetRefreshCounter();
  51784. continue;
  51785. }
  51786. mesh._preActivateForIntermediateRendering(sceneRenderId);
  51787. var isMasked = void 0;
  51788. if (!this.renderList && camera) {
  51789. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  51790. }
  51791. else {
  51792. isMasked = false;
  51793. }
  51794. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  51795. mesh._activate(sceneRenderId);
  51796. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  51797. var subMesh = mesh.subMeshes[subIndex];
  51798. scene._activeIndices.addCount(subMesh.indexCount, false);
  51799. this._renderingManager.dispatch(subMesh, mesh);
  51800. }
  51801. }
  51802. }
  51803. }
  51804. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  51805. var particleSystem = scene.particleSystems[particleIndex];
  51806. var emitter = particleSystem.emitter;
  51807. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  51808. continue;
  51809. }
  51810. if (currentRenderList.indexOf(emitter) >= 0) {
  51811. this._renderingManager.dispatchParticles(particleSystem);
  51812. }
  51813. }
  51814. if (this.isCube) {
  51815. for (var face = 0; face < 6; face++) {
  51816. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  51817. scene.incrementRenderId();
  51818. scene.resetCachedMaterial();
  51819. }
  51820. }
  51821. else {
  51822. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  51823. }
  51824. this.onAfterUnbindObservable.notifyObservers(this);
  51825. if (scene.activeCamera) {
  51826. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  51827. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  51828. }
  51829. engine.setViewport(scene.activeCamera.viewport);
  51830. }
  51831. scene.resetCachedMaterial();
  51832. };
  51833. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  51834. var minimum = 128;
  51835. var x = renderDimension * scale;
  51836. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  51837. // Ensure we don't exceed the render dimension (while staying POT)
  51838. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  51839. };
  51840. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  51841. var _this = this;
  51842. if (!this._texture) {
  51843. return;
  51844. }
  51845. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  51846. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  51847. });
  51848. };
  51849. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  51850. var scene = this.getScene();
  51851. if (!scene) {
  51852. return;
  51853. }
  51854. var engine = scene.getEngine();
  51855. if (!this._texture) {
  51856. return;
  51857. }
  51858. // Bind
  51859. if (this._postProcessManager) {
  51860. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  51861. }
  51862. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  51863. if (this._texture) {
  51864. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  51865. }
  51866. }
  51867. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  51868. // Clear
  51869. if (this.onClearObservable.hasObservers()) {
  51870. this.onClearObservable.notifyObservers(engine);
  51871. }
  51872. else {
  51873. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  51874. }
  51875. if (!this._doNotChangeAspectRatio) {
  51876. scene.updateTransformMatrix(true);
  51877. }
  51878. // Render
  51879. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  51880. if (this._postProcessManager) {
  51881. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  51882. }
  51883. else if (useCameraPostProcess) {
  51884. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  51885. }
  51886. if (!this._doNotChangeAspectRatio) {
  51887. scene.updateTransformMatrix(true);
  51888. }
  51889. // Dump ?
  51890. if (dumpForDebug) {
  51891. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  51892. }
  51893. // Unbind
  51894. if (!this.isCube || faceIndex === 5) {
  51895. if (this.isCube) {
  51896. if (faceIndex === 5) {
  51897. engine.generateMipMapsForCubemap(this._texture);
  51898. }
  51899. }
  51900. this.unbindFrameBuffer(engine, faceIndex);
  51901. }
  51902. else {
  51903. this.onAfterRenderObservable.notifyObservers(faceIndex);
  51904. }
  51905. };
  51906. /**
  51907. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  51908. * This allowed control for front to back rendering or reversly depending of the special needs.
  51909. *
  51910. * @param renderingGroupId The rendering group id corresponding to its index
  51911. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  51912. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  51913. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  51914. */
  51915. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  51916. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  51917. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  51918. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  51919. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  51920. };
  51921. /**
  51922. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  51923. *
  51924. * @param renderingGroupId The rendering group id corresponding to its index
  51925. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  51926. */
  51927. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  51928. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  51929. };
  51930. RenderTargetTexture.prototype.clone = function () {
  51931. var textureSize = this.getSize();
  51932. 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);
  51933. // Base texture
  51934. newTexture.hasAlpha = this.hasAlpha;
  51935. newTexture.level = this.level;
  51936. // RenderTarget Texture
  51937. newTexture.coordinatesMode = this.coordinatesMode;
  51938. if (this.renderList) {
  51939. newTexture.renderList = this.renderList.slice(0);
  51940. }
  51941. return newTexture;
  51942. };
  51943. RenderTargetTexture.prototype.serialize = function () {
  51944. if (!this.name) {
  51945. return null;
  51946. }
  51947. var serializationObject = _super.prototype.serialize.call(this);
  51948. serializationObject.renderTargetSize = this.getRenderSize();
  51949. serializationObject.renderList = [];
  51950. if (this.renderList) {
  51951. for (var index = 0; index < this.renderList.length; index++) {
  51952. serializationObject.renderList.push(this.renderList[index].id);
  51953. }
  51954. }
  51955. return serializationObject;
  51956. };
  51957. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  51958. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  51959. var objBuffer = this.getInternalTexture();
  51960. var scene = this.getScene();
  51961. if (objBuffer && scene) {
  51962. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  51963. }
  51964. };
  51965. RenderTargetTexture.prototype.dispose = function () {
  51966. if (this._postProcessManager) {
  51967. this._postProcessManager.dispose();
  51968. this._postProcessManager = null;
  51969. }
  51970. this.clearPostProcesses(true);
  51971. if (this._resizeObserver) {
  51972. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  51973. this._resizeObserver = null;
  51974. }
  51975. this.renderList = null;
  51976. // Remove from custom render targets
  51977. var scene = this.getScene();
  51978. if (!scene) {
  51979. return;
  51980. }
  51981. var index = scene.customRenderTargets.indexOf(this);
  51982. if (index >= 0) {
  51983. scene.customRenderTargets.splice(index, 1);
  51984. }
  51985. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  51986. var camera = _a[_i];
  51987. index = camera.customRenderTargets.indexOf(this);
  51988. if (index >= 0) {
  51989. camera.customRenderTargets.splice(index, 1);
  51990. }
  51991. }
  51992. _super.prototype.dispose.call(this);
  51993. };
  51994. RenderTargetTexture.prototype._rebuild = function () {
  51995. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  51996. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  51997. }
  51998. if (this._postProcessManager) {
  51999. this._postProcessManager._rebuild();
  52000. }
  52001. };
  52002. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  52003. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  52004. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  52005. return RenderTargetTexture;
  52006. }(BABYLON.Texture));
  52007. BABYLON.RenderTargetTexture = RenderTargetTexture;
  52008. })(BABYLON || (BABYLON = {}));
  52009. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  52010. var BABYLON;
  52011. (function (BABYLON) {
  52012. ;
  52013. var MultiRenderTarget = /** @class */ (function (_super) {
  52014. __extends(MultiRenderTarget, _super);
  52015. function MultiRenderTarget(name, size, count, scene, options) {
  52016. var _this = this;
  52017. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  52018. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  52019. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  52020. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  52021. _this._engine = scene.getEngine();
  52022. if (!_this.isSupported) {
  52023. _this.dispose();
  52024. return;
  52025. }
  52026. var types = [];
  52027. var samplingModes = [];
  52028. for (var i = 0; i < count; i++) {
  52029. if (options && options.types && options.types[i] !== undefined) {
  52030. types.push(options.types[i]);
  52031. }
  52032. else {
  52033. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  52034. }
  52035. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  52036. samplingModes.push(options.samplingModes[i]);
  52037. }
  52038. else {
  52039. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52040. }
  52041. }
  52042. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  52043. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  52044. _this._size = size;
  52045. _this._multiRenderTargetOptions = {
  52046. samplingModes: samplingModes,
  52047. generateMipMaps: generateMipMaps,
  52048. generateDepthBuffer: generateDepthBuffer,
  52049. generateStencilBuffer: generateStencilBuffer,
  52050. generateDepthTexture: generateDepthTexture,
  52051. types: types,
  52052. textureCount: count
  52053. };
  52054. _this._createInternalTextures();
  52055. _this._createTextures();
  52056. return _this;
  52057. }
  52058. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  52059. get: function () {
  52060. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  52061. },
  52062. enumerable: true,
  52063. configurable: true
  52064. });
  52065. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  52066. get: function () {
  52067. return this._textures;
  52068. },
  52069. enumerable: true,
  52070. configurable: true
  52071. });
  52072. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  52073. get: function () {
  52074. return this._textures[this._textures.length - 1];
  52075. },
  52076. enumerable: true,
  52077. configurable: true
  52078. });
  52079. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  52080. set: function (wrap) {
  52081. if (this._textures) {
  52082. for (var i = 0; i < this._textures.length; i++) {
  52083. this._textures[i].wrapU = wrap;
  52084. }
  52085. }
  52086. },
  52087. enumerable: true,
  52088. configurable: true
  52089. });
  52090. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  52091. set: function (wrap) {
  52092. if (this._textures) {
  52093. for (var i = 0; i < this._textures.length; i++) {
  52094. this._textures[i].wrapV = wrap;
  52095. }
  52096. }
  52097. },
  52098. enumerable: true,
  52099. configurable: true
  52100. });
  52101. MultiRenderTarget.prototype._rebuild = function () {
  52102. this.releaseInternalTextures();
  52103. this._createInternalTextures();
  52104. for (var i = 0; i < this._internalTextures.length; i++) {
  52105. var texture = this._textures[i];
  52106. texture._texture = this._internalTextures[i];
  52107. }
  52108. // Keeps references to frame buffer and stencil/depth buffer
  52109. this._texture = this._internalTextures[0];
  52110. };
  52111. MultiRenderTarget.prototype._createInternalTextures = function () {
  52112. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  52113. };
  52114. MultiRenderTarget.prototype._createTextures = function () {
  52115. this._textures = [];
  52116. for (var i = 0; i < this._internalTextures.length; i++) {
  52117. var texture = new BABYLON.Texture(null, this.getScene());
  52118. texture._texture = this._internalTextures[i];
  52119. this._textures.push(texture);
  52120. }
  52121. // Keeps references to frame buffer and stencil/depth buffer
  52122. this._texture = this._internalTextures[0];
  52123. };
  52124. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  52125. get: function () {
  52126. return this._samples;
  52127. },
  52128. set: function (value) {
  52129. if (this._samples === value) {
  52130. return;
  52131. }
  52132. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  52133. },
  52134. enumerable: true,
  52135. configurable: true
  52136. });
  52137. MultiRenderTarget.prototype.resize = function (size) {
  52138. this.releaseInternalTextures();
  52139. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  52140. this._createInternalTextures();
  52141. };
  52142. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  52143. var _this = this;
  52144. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  52145. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  52146. });
  52147. };
  52148. MultiRenderTarget.prototype.dispose = function () {
  52149. this.releaseInternalTextures();
  52150. _super.prototype.dispose.call(this);
  52151. };
  52152. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  52153. if (!this._internalTextures) {
  52154. return;
  52155. }
  52156. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  52157. if (this._internalTextures[i] !== undefined) {
  52158. this._internalTextures[i].dispose();
  52159. this._internalTextures.splice(i, 1);
  52160. }
  52161. }
  52162. };
  52163. return MultiRenderTarget;
  52164. }(BABYLON.RenderTargetTexture));
  52165. BABYLON.MultiRenderTarget = MultiRenderTarget;
  52166. })(BABYLON || (BABYLON = {}));
  52167. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  52168. var BABYLON;
  52169. (function (BABYLON) {
  52170. var MirrorTexture = /** @class */ (function (_super) {
  52171. __extends(MirrorTexture, _super);
  52172. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  52173. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52174. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  52175. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  52176. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  52177. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  52178. _this._transformMatrix = BABYLON.Matrix.Zero();
  52179. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  52180. _this._adaptiveBlurKernel = 0;
  52181. _this._blurKernelX = 0;
  52182. _this._blurKernelY = 0;
  52183. _this._blurRatio = 1.0;
  52184. _this.ignoreCameraViewport = true;
  52185. _this.onBeforeRenderObservable.add(function () {
  52186. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  52187. _this._savedViewMatrix = scene.getViewMatrix();
  52188. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  52189. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  52190. scene.clipPlane = _this.mirrorPlane;
  52191. scene.getEngine().cullBackFaces = false;
  52192. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  52193. });
  52194. _this.onAfterRenderObservable.add(function () {
  52195. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  52196. scene.getEngine().cullBackFaces = true;
  52197. scene._mirroredCameraPosition = null;
  52198. delete scene.clipPlane;
  52199. });
  52200. return _this;
  52201. }
  52202. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  52203. get: function () {
  52204. return this._blurRatio;
  52205. },
  52206. set: function (value) {
  52207. if (this._blurRatio === value) {
  52208. return;
  52209. }
  52210. this._blurRatio = value;
  52211. this._preparePostProcesses();
  52212. },
  52213. enumerable: true,
  52214. configurable: true
  52215. });
  52216. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  52217. set: function (value) {
  52218. this._adaptiveBlurKernel = value;
  52219. this._autoComputeBlurKernel();
  52220. },
  52221. enumerable: true,
  52222. configurable: true
  52223. });
  52224. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  52225. set: function (value) {
  52226. this.blurKernelX = value;
  52227. this.blurKernelY = value;
  52228. },
  52229. enumerable: true,
  52230. configurable: true
  52231. });
  52232. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  52233. get: function () {
  52234. return this._blurKernelX;
  52235. },
  52236. set: function (value) {
  52237. if (this._blurKernelX === value) {
  52238. return;
  52239. }
  52240. this._blurKernelX = value;
  52241. this._preparePostProcesses();
  52242. },
  52243. enumerable: true,
  52244. configurable: true
  52245. });
  52246. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  52247. get: function () {
  52248. return this._blurKernelY;
  52249. },
  52250. set: function (value) {
  52251. if (this._blurKernelY === value) {
  52252. return;
  52253. }
  52254. this._blurKernelY = value;
  52255. this._preparePostProcesses();
  52256. },
  52257. enumerable: true,
  52258. configurable: true
  52259. });
  52260. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  52261. var engine = this.getScene().getEngine();
  52262. var dw = this.getRenderWidth() / engine.getRenderWidth();
  52263. var dh = this.getRenderHeight() / engine.getRenderHeight();
  52264. this.blurKernelX = this._adaptiveBlurKernel * dw;
  52265. this.blurKernelY = this._adaptiveBlurKernel * dh;
  52266. };
  52267. MirrorTexture.prototype._onRatioRescale = function () {
  52268. if (this._sizeRatio) {
  52269. this.resize(this._initialSizeParameter);
  52270. if (!this._adaptiveBlurKernel) {
  52271. this._preparePostProcesses();
  52272. }
  52273. }
  52274. if (this._adaptiveBlurKernel) {
  52275. this._autoComputeBlurKernel();
  52276. }
  52277. };
  52278. MirrorTexture.prototype._preparePostProcesses = function () {
  52279. this.clearPostProcesses(true);
  52280. if (this._blurKernelX && this._blurKernelY) {
  52281. var engine = this.getScene().getEngine();
  52282. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  52283. 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);
  52284. this._blurX.autoClear = false;
  52285. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  52286. this._blurX.outputTexture = this._texture;
  52287. }
  52288. else {
  52289. this._blurX.alwaysForcePOT = true;
  52290. }
  52291. 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);
  52292. this._blurY.autoClear = false;
  52293. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  52294. this.addPostProcess(this._blurX);
  52295. this.addPostProcess(this._blurY);
  52296. }
  52297. else {
  52298. if (this._blurY) {
  52299. this.removePostProcess(this._blurY);
  52300. this._blurY.dispose();
  52301. this._blurY = null;
  52302. }
  52303. if (this._blurX) {
  52304. this.removePostProcess(this._blurX);
  52305. this._blurX.dispose();
  52306. this._blurX = null;
  52307. }
  52308. }
  52309. };
  52310. MirrorTexture.prototype.clone = function () {
  52311. var scene = this.getScene();
  52312. if (!scene) {
  52313. return this;
  52314. }
  52315. var textureSize = this.getSize();
  52316. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  52317. // Base texture
  52318. newTexture.hasAlpha = this.hasAlpha;
  52319. newTexture.level = this.level;
  52320. // Mirror Texture
  52321. newTexture.mirrorPlane = this.mirrorPlane.clone();
  52322. if (this.renderList) {
  52323. newTexture.renderList = this.renderList.slice(0);
  52324. }
  52325. return newTexture;
  52326. };
  52327. MirrorTexture.prototype.serialize = function () {
  52328. if (!this.name) {
  52329. return null;
  52330. }
  52331. var serializationObject = _super.prototype.serialize.call(this);
  52332. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  52333. return serializationObject;
  52334. };
  52335. return MirrorTexture;
  52336. }(BABYLON.RenderTargetTexture));
  52337. BABYLON.MirrorTexture = MirrorTexture;
  52338. })(BABYLON || (BABYLON = {}));
  52339. //# sourceMappingURL=babylon.mirrorTexture.js.map
  52340. var BABYLON;
  52341. (function (BABYLON) {
  52342. /**
  52343. * Creates a refraction texture used by refraction channel of the standard material.
  52344. * @param name the texture name
  52345. * @param size size of the underlying texture
  52346. * @param scene root scene
  52347. */
  52348. var RefractionTexture = /** @class */ (function (_super) {
  52349. __extends(RefractionTexture, _super);
  52350. function RefractionTexture(name, size, scene, generateMipMaps) {
  52351. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  52352. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  52353. _this.depth = 2.0;
  52354. _this.onBeforeRenderObservable.add(function () {
  52355. scene.clipPlane = _this.refractionPlane;
  52356. });
  52357. _this.onAfterRenderObservable.add(function () {
  52358. delete scene.clipPlane;
  52359. });
  52360. return _this;
  52361. }
  52362. RefractionTexture.prototype.clone = function () {
  52363. var scene = this.getScene();
  52364. if (!scene) {
  52365. return this;
  52366. }
  52367. var textureSize = this.getSize();
  52368. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  52369. // Base texture
  52370. newTexture.hasAlpha = this.hasAlpha;
  52371. newTexture.level = this.level;
  52372. // Refraction Texture
  52373. newTexture.refractionPlane = this.refractionPlane.clone();
  52374. if (this.renderList) {
  52375. newTexture.renderList = this.renderList.slice(0);
  52376. }
  52377. newTexture.depth = this.depth;
  52378. return newTexture;
  52379. };
  52380. RefractionTexture.prototype.serialize = function () {
  52381. if (!this.name) {
  52382. return null;
  52383. }
  52384. var serializationObject = _super.prototype.serialize.call(this);
  52385. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  52386. serializationObject.depth = this.depth;
  52387. return serializationObject;
  52388. };
  52389. return RefractionTexture;
  52390. }(BABYLON.RenderTargetTexture));
  52391. BABYLON.RefractionTexture = RefractionTexture;
  52392. })(BABYLON || (BABYLON = {}));
  52393. //# sourceMappingURL=babylon.refractionTexture.js.map
  52394. var BABYLON;
  52395. (function (BABYLON) {
  52396. var DynamicTexture = /** @class */ (function (_super) {
  52397. __extends(DynamicTexture, _super);
  52398. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  52399. if (scene === void 0) { scene = null; }
  52400. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52401. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  52402. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  52403. _this.name = name;
  52404. _this._engine = _this.getScene().getEngine();
  52405. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52406. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52407. _this._generateMipMaps = generateMipMaps;
  52408. if (options.getContext) {
  52409. _this._canvas = options;
  52410. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  52411. }
  52412. else {
  52413. _this._canvas = document.createElement("canvas");
  52414. if (options.width) {
  52415. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  52416. }
  52417. else {
  52418. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  52419. }
  52420. }
  52421. var textureSize = _this.getSize();
  52422. _this._canvas.width = textureSize.width;
  52423. _this._canvas.height = textureSize.height;
  52424. _this._context = _this._canvas.getContext("2d");
  52425. return _this;
  52426. }
  52427. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  52428. get: function () {
  52429. return true;
  52430. },
  52431. enumerable: true,
  52432. configurable: true
  52433. });
  52434. DynamicTexture.prototype._recreate = function (textureSize) {
  52435. this._canvas.width = textureSize.width;
  52436. this._canvas.height = textureSize.height;
  52437. this.releaseInternalTexture();
  52438. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  52439. };
  52440. DynamicTexture.prototype.scale = function (ratio) {
  52441. var textureSize = this.getSize();
  52442. textureSize.width *= ratio;
  52443. textureSize.height *= ratio;
  52444. this._recreate(textureSize);
  52445. };
  52446. DynamicTexture.prototype.scaleTo = function (width, height) {
  52447. var textureSize = this.getSize();
  52448. textureSize.width = width;
  52449. textureSize.height = height;
  52450. this._recreate(textureSize);
  52451. };
  52452. DynamicTexture.prototype.getContext = function () {
  52453. return this._context;
  52454. };
  52455. DynamicTexture.prototype.clear = function () {
  52456. var size = this.getSize();
  52457. this._context.fillRect(0, 0, size.width, size.height);
  52458. };
  52459. DynamicTexture.prototype.update = function (invertY) {
  52460. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  52461. };
  52462. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  52463. if (update === void 0) { update = true; }
  52464. var size = this.getSize();
  52465. if (clearColor) {
  52466. this._context.fillStyle = clearColor;
  52467. this._context.fillRect(0, 0, size.width, size.height);
  52468. }
  52469. this._context.font = font;
  52470. if (x === null || x === undefined) {
  52471. var textSize = this._context.measureText(text);
  52472. x = (size.width - textSize.width) / 2;
  52473. }
  52474. if (y === null || y === undefined) {
  52475. var fontSize = parseInt((font.replace(/\D/g, '')));
  52476. ;
  52477. y = (size.height / 2) + (fontSize / 3.65);
  52478. }
  52479. this._context.fillStyle = color;
  52480. this._context.fillText(text, x, y);
  52481. if (update) {
  52482. this.update(invertY);
  52483. }
  52484. };
  52485. DynamicTexture.prototype.clone = function () {
  52486. var scene = this.getScene();
  52487. if (!scene) {
  52488. return this;
  52489. }
  52490. var textureSize = this.getSize();
  52491. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  52492. // Base texture
  52493. newTexture.hasAlpha = this.hasAlpha;
  52494. newTexture.level = this.level;
  52495. // Dynamic Texture
  52496. newTexture.wrapU = this.wrapU;
  52497. newTexture.wrapV = this.wrapV;
  52498. return newTexture;
  52499. };
  52500. DynamicTexture.prototype._rebuild = function () {
  52501. this.update();
  52502. };
  52503. return DynamicTexture;
  52504. }(BABYLON.Texture));
  52505. BABYLON.DynamicTexture = DynamicTexture;
  52506. })(BABYLON || (BABYLON = {}));
  52507. //# sourceMappingURL=babylon.dynamicTexture.js.map
  52508. var BABYLON;
  52509. (function (BABYLON) {
  52510. var VideoTexture = /** @class */ (function (_super) {
  52511. __extends(VideoTexture, _super);
  52512. /**
  52513. * Creates a video texture.
  52514. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  52515. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  52516. * @param {BABYLON.Scene} scene is obviously the current scene.
  52517. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  52518. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  52519. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  52520. */
  52521. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  52522. if (generateMipMaps === void 0) { generateMipMaps = false; }
  52523. if (invertY === void 0) { invertY = false; }
  52524. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52525. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  52526. _this._autoLaunch = true;
  52527. var urls = null;
  52528. _this.name = name;
  52529. if (urlsOrVideo instanceof HTMLVideoElement) {
  52530. _this.video = urlsOrVideo;
  52531. }
  52532. else {
  52533. urls = urlsOrVideo;
  52534. _this.video = document.createElement("video");
  52535. _this.video.autoplay = false;
  52536. _this.video.loop = true;
  52537. BABYLON.Tools.SetCorsBehavior(urls, _this.video);
  52538. }
  52539. _this._engine = _this.getScene().getEngine();
  52540. _this._generateMipMaps = generateMipMaps;
  52541. _this._samplingMode = samplingMode;
  52542. if (!_this._engine.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  52543. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  52544. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  52545. }
  52546. else {
  52547. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52548. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52549. _this._generateMipMaps = false;
  52550. }
  52551. if (urls) {
  52552. _this.video.addEventListener("canplay", function () {
  52553. if (_this._texture === undefined) {
  52554. _this._createTexture();
  52555. }
  52556. });
  52557. urls.forEach(function (url) {
  52558. var source = document.createElement("source");
  52559. source.src = url;
  52560. _this.video.appendChild(source);
  52561. });
  52562. }
  52563. else {
  52564. _this._createTexture();
  52565. }
  52566. _this._lastUpdate = BABYLON.Tools.Now;
  52567. return _this;
  52568. }
  52569. VideoTexture.prototype.__setTextureReady = function () {
  52570. if (this._texture) {
  52571. this._texture.isReady = true;
  52572. }
  52573. };
  52574. VideoTexture.prototype._createTexture = function () {
  52575. this._texture = this._engine.createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  52576. if (this._autoLaunch) {
  52577. this._autoLaunch = false;
  52578. this.video.play();
  52579. }
  52580. this._setTextureReady = this.__setTextureReady.bind(this);
  52581. this.video.addEventListener("playing", this._setTextureReady);
  52582. };
  52583. VideoTexture.prototype._rebuild = function () {
  52584. this.update();
  52585. };
  52586. VideoTexture.prototype.update = function () {
  52587. var now = BABYLON.Tools.Now;
  52588. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  52589. return false;
  52590. }
  52591. this._lastUpdate = now;
  52592. this._engine.updateVideoTexture(this._texture, this.video, this._invertY);
  52593. return true;
  52594. };
  52595. VideoTexture.prototype.dispose = function () {
  52596. _super.prototype.dispose.call(this);
  52597. this.video.removeEventListener("playing", this._setTextureReady);
  52598. };
  52599. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  52600. var video = document.createElement("video");
  52601. var constraintsDeviceId;
  52602. if (constraints && constraints.deviceId) {
  52603. constraintsDeviceId = {
  52604. exact: constraints.deviceId
  52605. };
  52606. }
  52607. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  52608. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  52609. if (navigator.getUserMedia) {
  52610. navigator.getUserMedia({
  52611. video: {
  52612. deviceId: constraintsDeviceId,
  52613. width: {
  52614. min: (constraints && constraints.minWidth) || 256,
  52615. max: (constraints && constraints.maxWidth) || 640
  52616. },
  52617. height: {
  52618. min: (constraints && constraints.minHeight) || 256,
  52619. max: (constraints && constraints.maxHeight) || 480
  52620. }
  52621. }
  52622. }, function (stream) {
  52623. if (video.mozSrcObject !== undefined) {
  52624. video.mozSrcObject = stream;
  52625. }
  52626. else {
  52627. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  52628. }
  52629. video.play();
  52630. if (onReady) {
  52631. onReady(new VideoTexture("video", video, scene, true, true));
  52632. }
  52633. }, function (e) {
  52634. BABYLON.Tools.Error(e.name);
  52635. });
  52636. }
  52637. };
  52638. return VideoTexture;
  52639. }(BABYLON.Texture));
  52640. BABYLON.VideoTexture = VideoTexture;
  52641. })(BABYLON || (BABYLON = {}));
  52642. //# sourceMappingURL=babylon.videoTexture.js.map
  52643. var BABYLON;
  52644. (function (BABYLON) {
  52645. var RawTexture = /** @class */ (function (_super) {
  52646. __extends(RawTexture, _super);
  52647. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  52648. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52649. if (invertY === void 0) { invertY = false; }
  52650. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52651. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52652. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  52653. _this.format = format;
  52654. _this._engine = scene.getEngine();
  52655. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  52656. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52657. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52658. return _this;
  52659. }
  52660. RawTexture.prototype.update = function (data) {
  52661. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  52662. };
  52663. // Statics
  52664. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  52665. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52666. if (invertY === void 0) { invertY = false; }
  52667. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52668. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  52669. };
  52670. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  52671. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52672. if (invertY === void 0) { invertY = false; }
  52673. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52674. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  52675. };
  52676. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  52677. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52678. if (invertY === void 0) { invertY = false; }
  52679. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52680. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  52681. };
  52682. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  52683. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52684. if (invertY === void 0) { invertY = false; }
  52685. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52686. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52687. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  52688. };
  52689. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  52690. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52691. if (invertY === void 0) { invertY = false; }
  52692. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52693. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52694. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  52695. };
  52696. return RawTexture;
  52697. }(BABYLON.Texture));
  52698. BABYLON.RawTexture = RawTexture;
  52699. })(BABYLON || (BABYLON = {}));
  52700. //# sourceMappingURL=babylon.rawTexture.js.map
  52701. var BABYLON;
  52702. (function (BABYLON) {
  52703. var PostProcess = /** @class */ (function () {
  52704. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  52705. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  52706. if (defines === void 0) { defines = null; }
  52707. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52708. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  52709. if (blockCompilation === void 0) { blockCompilation = false; }
  52710. this.name = name;
  52711. this.width = -1;
  52712. this.height = -1;
  52713. this.autoClear = true;
  52714. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  52715. this.animations = new Array();
  52716. /*
  52717. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  52718. Can only be used on a single postprocess or on the last one of a chain.
  52719. */
  52720. this.enablePixelPerfectMode = false;
  52721. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  52722. this.alwaysForcePOT = false;
  52723. this.samples = 1;
  52724. this.adaptScaleToCurrentViewport = false;
  52725. this._reusable = false;
  52726. this._textures = new BABYLON.SmartArray(2);
  52727. this._currentRenderTextureInd = 0;
  52728. this._scaleRatio = new BABYLON.Vector2(1, 1);
  52729. this._texelSize = BABYLON.Vector2.Zero();
  52730. // Events
  52731. /**
  52732. * An event triggered when the postprocess is activated.
  52733. * @type {BABYLON.Observable}
  52734. */
  52735. this.onActivateObservable = new BABYLON.Observable();
  52736. /**
  52737. * An event triggered when the postprocess changes its size.
  52738. * @type {BABYLON.Observable}
  52739. */
  52740. this.onSizeChangedObservable = new BABYLON.Observable();
  52741. /**
  52742. * An event triggered when the postprocess applies its effect.
  52743. * @type {BABYLON.Observable}
  52744. */
  52745. this.onApplyObservable = new BABYLON.Observable();
  52746. /**
  52747. * An event triggered before rendering the postprocess
  52748. * @type {BABYLON.Observable}
  52749. */
  52750. this.onBeforeRenderObservable = new BABYLON.Observable();
  52751. /**
  52752. * An event triggered after rendering the postprocess
  52753. * @type {BABYLON.Observable}
  52754. */
  52755. this.onAfterRenderObservable = new BABYLON.Observable();
  52756. if (camera != null) {
  52757. this._camera = camera;
  52758. this._scene = camera.getScene();
  52759. camera.attachPostProcess(this);
  52760. this._engine = this._scene.getEngine();
  52761. this._scene.postProcesses.push(this);
  52762. }
  52763. else if (engine) {
  52764. this._engine = engine;
  52765. this._engine.postProcesses.push(this);
  52766. }
  52767. this._options = options;
  52768. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  52769. this._reusable = reusable || false;
  52770. this._textureType = textureType;
  52771. this._samplers = samplers || [];
  52772. this._samplers.push("textureSampler");
  52773. this._fragmentUrl = fragmentUrl;
  52774. this._vertexUrl = vertexUrl;
  52775. this._parameters = parameters || [];
  52776. this._parameters.push("scale");
  52777. this._indexParameters = indexParameters;
  52778. if (!blockCompilation) {
  52779. this.updateEffect(defines);
  52780. }
  52781. }
  52782. Object.defineProperty(PostProcess.prototype, "onActivate", {
  52783. set: function (callback) {
  52784. if (this._onActivateObserver) {
  52785. this.onActivateObservable.remove(this._onActivateObserver);
  52786. }
  52787. if (callback) {
  52788. this._onActivateObserver = this.onActivateObservable.add(callback);
  52789. }
  52790. },
  52791. enumerable: true,
  52792. configurable: true
  52793. });
  52794. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  52795. set: function (callback) {
  52796. if (this._onSizeChangedObserver) {
  52797. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  52798. }
  52799. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  52800. },
  52801. enumerable: true,
  52802. configurable: true
  52803. });
  52804. Object.defineProperty(PostProcess.prototype, "onApply", {
  52805. set: function (callback) {
  52806. if (this._onApplyObserver) {
  52807. this.onApplyObservable.remove(this._onApplyObserver);
  52808. }
  52809. this._onApplyObserver = this.onApplyObservable.add(callback);
  52810. },
  52811. enumerable: true,
  52812. configurable: true
  52813. });
  52814. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  52815. set: function (callback) {
  52816. if (this._onBeforeRenderObserver) {
  52817. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  52818. }
  52819. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  52820. },
  52821. enumerable: true,
  52822. configurable: true
  52823. });
  52824. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  52825. set: function (callback) {
  52826. if (this._onAfterRenderObserver) {
  52827. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  52828. }
  52829. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  52830. },
  52831. enumerable: true,
  52832. configurable: true
  52833. });
  52834. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  52835. get: function () {
  52836. return this._textures.data[this._currentRenderTextureInd];
  52837. },
  52838. set: function (value) {
  52839. this._forcedOutputTexture = value;
  52840. },
  52841. enumerable: true,
  52842. configurable: true
  52843. });
  52844. PostProcess.prototype.getCamera = function () {
  52845. return this._camera;
  52846. };
  52847. Object.defineProperty(PostProcess.prototype, "texelSize", {
  52848. get: function () {
  52849. if (this._shareOutputWithPostProcess) {
  52850. return this._shareOutputWithPostProcess.texelSize;
  52851. }
  52852. if (this._forcedOutputTexture) {
  52853. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  52854. }
  52855. return this._texelSize;
  52856. },
  52857. enumerable: true,
  52858. configurable: true
  52859. });
  52860. PostProcess.prototype.getEngine = function () {
  52861. return this._engine;
  52862. };
  52863. PostProcess.prototype.getEffect = function () {
  52864. return this._effect;
  52865. };
  52866. PostProcess.prototype.shareOutputWith = function (postProcess) {
  52867. this._disposeTextures();
  52868. this._shareOutputWithPostProcess = postProcess;
  52869. return this;
  52870. };
  52871. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  52872. if (defines === void 0) { defines = null; }
  52873. if (uniforms === void 0) { uniforms = null; }
  52874. if (samplers === void 0) { samplers = null; }
  52875. 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);
  52876. };
  52877. PostProcess.prototype.isReusable = function () {
  52878. return this._reusable;
  52879. };
  52880. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  52881. PostProcess.prototype.markTextureDirty = function () {
  52882. this.width = -1;
  52883. };
  52884. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  52885. var _this = this;
  52886. if (sourceTexture === void 0) { sourceTexture = null; }
  52887. camera = camera || this._camera;
  52888. var scene = camera.getScene();
  52889. var engine = scene.getEngine();
  52890. var maxSize = engine.getCaps().maxTextureSize;
  52891. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  52892. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  52893. var desiredWidth = (this._options.width || requiredWidth);
  52894. var desiredHeight = this._options.height || requiredHeight;
  52895. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  52896. if (this.adaptScaleToCurrentViewport) {
  52897. var currentViewport = engine.currentViewport;
  52898. if (currentViewport) {
  52899. desiredWidth *= currentViewport.width;
  52900. desiredHeight *= currentViewport.height;
  52901. }
  52902. }
  52903. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  52904. if (!this._options.width) {
  52905. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  52906. }
  52907. if (!this._options.height) {
  52908. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  52909. }
  52910. }
  52911. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  52912. if (this._textures.length > 0) {
  52913. for (var i = 0; i < this._textures.length; i++) {
  52914. this._engine._releaseTexture(this._textures.data[i]);
  52915. }
  52916. this._textures.reset();
  52917. }
  52918. this.width = desiredWidth;
  52919. this.height = desiredHeight;
  52920. var textureSize = { width: this.width, height: this.height };
  52921. var textureOptions = {
  52922. generateMipMaps: false,
  52923. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  52924. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  52925. samplingMode: this.renderTargetSamplingMode,
  52926. type: this._textureType
  52927. };
  52928. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  52929. if (this._reusable) {
  52930. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  52931. }
  52932. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  52933. this.onSizeChangedObservable.notifyObservers(this);
  52934. }
  52935. this._textures.forEach(function (texture) {
  52936. if (texture.samples !== _this.samples) {
  52937. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  52938. }
  52939. });
  52940. }
  52941. var target;
  52942. if (this._shareOutputWithPostProcess) {
  52943. target = this._shareOutputWithPostProcess.outputTexture;
  52944. }
  52945. else if (this._forcedOutputTexture) {
  52946. target = this._forcedOutputTexture;
  52947. this.width = this._forcedOutputTexture.width;
  52948. this.height = this._forcedOutputTexture.height;
  52949. }
  52950. else {
  52951. target = this.outputTexture;
  52952. }
  52953. if (this.enablePixelPerfectMode) {
  52954. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  52955. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  52956. }
  52957. else {
  52958. this._scaleRatio.copyFromFloats(1, 1);
  52959. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  52960. }
  52961. this.onActivateObservable.notifyObservers(camera);
  52962. // Clear
  52963. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  52964. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  52965. }
  52966. if (this._reusable) {
  52967. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  52968. }
  52969. };
  52970. Object.defineProperty(PostProcess.prototype, "isSupported", {
  52971. get: function () {
  52972. return this._effect.isSupported;
  52973. },
  52974. enumerable: true,
  52975. configurable: true
  52976. });
  52977. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  52978. get: function () {
  52979. if (this._shareOutputWithPostProcess) {
  52980. return this._shareOutputWithPostProcess.aspectRatio;
  52981. }
  52982. if (this._forcedOutputTexture) {
  52983. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  52984. }
  52985. return this.width / this.height;
  52986. },
  52987. enumerable: true,
  52988. configurable: true
  52989. });
  52990. PostProcess.prototype.apply = function () {
  52991. // Check
  52992. if (!this._effect || !this._effect.isReady())
  52993. return null;
  52994. // States
  52995. this._engine.enableEffect(this._effect);
  52996. this._engine.setState(false);
  52997. this._engine.setDepthBuffer(false);
  52998. this._engine.setDepthWrite(false);
  52999. // Alpha
  53000. this._engine.setAlphaMode(this.alphaMode);
  53001. if (this.alphaConstants) {
  53002. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  53003. }
  53004. // Texture
  53005. var source;
  53006. if (this._shareOutputWithPostProcess) {
  53007. source = this._shareOutputWithPostProcess.outputTexture;
  53008. }
  53009. else if (this._forcedOutputTexture) {
  53010. source = this._forcedOutputTexture;
  53011. }
  53012. else {
  53013. source = this.outputTexture;
  53014. }
  53015. this._effect._bindTexture("textureSampler", source);
  53016. // Parameters
  53017. this._effect.setVector2("scale", this._scaleRatio);
  53018. this.onApplyObservable.notifyObservers(this._effect);
  53019. return this._effect;
  53020. };
  53021. PostProcess.prototype._disposeTextures = function () {
  53022. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  53023. return;
  53024. }
  53025. if (this._textures.length > 0) {
  53026. for (var i = 0; i < this._textures.length; i++) {
  53027. this._engine._releaseTexture(this._textures.data[i]);
  53028. }
  53029. }
  53030. this._textures.dispose();
  53031. };
  53032. PostProcess.prototype.dispose = function (camera) {
  53033. camera = camera || this._camera;
  53034. this._disposeTextures();
  53035. if (this._scene) {
  53036. var index_1 = this._scene.postProcesses.indexOf(this);
  53037. if (index_1 !== -1) {
  53038. this._scene.postProcesses.splice(index_1, 1);
  53039. }
  53040. }
  53041. else {
  53042. var index_2 = this._engine.postProcesses.indexOf(this);
  53043. if (index_2 !== -1) {
  53044. this._engine.postProcesses.splice(index_2, 1);
  53045. }
  53046. }
  53047. if (!camera) {
  53048. return;
  53049. }
  53050. camera.detachPostProcess(this);
  53051. var index = camera._postProcesses.indexOf(this);
  53052. if (index === 0 && camera._postProcesses.length > 0) {
  53053. this._camera._postProcesses[0].markTextureDirty();
  53054. }
  53055. this.onActivateObservable.clear();
  53056. this.onAfterRenderObservable.clear();
  53057. this.onApplyObservable.clear();
  53058. this.onBeforeRenderObservable.clear();
  53059. this.onSizeChangedObservable.clear();
  53060. };
  53061. return PostProcess;
  53062. }());
  53063. BABYLON.PostProcess = PostProcess;
  53064. })(BABYLON || (BABYLON = {}));
  53065. //# sourceMappingURL=babylon.postProcess.js.map
  53066. var BABYLON;
  53067. (function (BABYLON) {
  53068. var PassPostProcess = /** @class */ (function (_super) {
  53069. __extends(PassPostProcess, _super);
  53070. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  53071. if (camera === void 0) { camera = null; }
  53072. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  53073. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  53074. }
  53075. return PassPostProcess;
  53076. }(BABYLON.PostProcess));
  53077. BABYLON.PassPostProcess = PassPostProcess;
  53078. })(BABYLON || (BABYLON = {}));
  53079. //# sourceMappingURL=babylon.passPostProcess.js.map
  53080. var __assign = (this && this.__assign) || Object.assign || function(t) {
  53081. for (var s, i = 1, n = arguments.length; i < n; i++) {
  53082. s = arguments[i];
  53083. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  53084. t[p] = s[p];
  53085. }
  53086. return t;
  53087. };
  53088. var BABYLON;
  53089. (function (BABYLON) {
  53090. var ShadowGenerator = /** @class */ (function () {
  53091. /**
  53092. * Creates a ShadowGenerator object.
  53093. * A ShadowGenerator is the required tool to use the shadows.
  53094. * Each light casting shadows needs to use its own ShadowGenerator.
  53095. * Required parameters :
  53096. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  53097. * - `light`: the light object generating the shadows.
  53098. * - `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.
  53099. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  53100. */
  53101. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  53102. // Members
  53103. this._bias = 0.00005;
  53104. this._blurBoxOffset = 1;
  53105. this._blurScale = 2;
  53106. this._blurKernel = 1;
  53107. this._useKernelBlur = false;
  53108. this._filter = ShadowGenerator.FILTER_NONE;
  53109. this._darkness = 0;
  53110. this._transparencyShadow = false;
  53111. /**
  53112. * Controls the extent to which the shadows fade out at the edge of the frustum
  53113. * Used only by directionals and spots
  53114. */
  53115. this.frustumEdgeFalloff = 0;
  53116. this.forceBackFacesOnly = false;
  53117. this._lightDirection = BABYLON.Vector3.Zero();
  53118. this._viewMatrix = BABYLON.Matrix.Zero();
  53119. this._projectionMatrix = BABYLON.Matrix.Zero();
  53120. this._transformMatrix = BABYLON.Matrix.Zero();
  53121. this._currentFaceIndex = 0;
  53122. this._currentFaceIndexCache = 0;
  53123. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  53124. this._mapSize = mapSize;
  53125. this._light = light;
  53126. this._scene = light.getScene();
  53127. light._shadowGenerator = this;
  53128. // Texture type fallback from float to int if not supported.
  53129. var caps = this._scene.getEngine().getCaps();
  53130. if (!useFullFloatFirst) {
  53131. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  53132. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  53133. }
  53134. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  53135. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  53136. }
  53137. else {
  53138. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  53139. }
  53140. }
  53141. else {
  53142. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  53143. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  53144. }
  53145. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  53146. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  53147. }
  53148. else {
  53149. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  53150. }
  53151. }
  53152. this._initializeGenerator();
  53153. }
  53154. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  53155. // Static
  53156. get: function () {
  53157. return ShadowGenerator._FILTER_NONE;
  53158. },
  53159. enumerable: true,
  53160. configurable: true
  53161. });
  53162. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  53163. get: function () {
  53164. return ShadowGenerator._FILTER_POISSONSAMPLING;
  53165. },
  53166. enumerable: true,
  53167. configurable: true
  53168. });
  53169. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  53170. get: function () {
  53171. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  53172. },
  53173. enumerable: true,
  53174. configurable: true
  53175. });
  53176. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  53177. get: function () {
  53178. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  53179. },
  53180. enumerable: true,
  53181. configurable: true
  53182. });
  53183. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  53184. get: function () {
  53185. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  53186. },
  53187. enumerable: true,
  53188. configurable: true
  53189. });
  53190. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  53191. get: function () {
  53192. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  53193. },
  53194. enumerable: true,
  53195. configurable: true
  53196. });
  53197. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  53198. get: function () {
  53199. return this._bias;
  53200. },
  53201. set: function (bias) {
  53202. this._bias = bias;
  53203. },
  53204. enumerable: true,
  53205. configurable: true
  53206. });
  53207. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  53208. get: function () {
  53209. return this._blurBoxOffset;
  53210. },
  53211. set: function (value) {
  53212. if (this._blurBoxOffset === value) {
  53213. return;
  53214. }
  53215. this._blurBoxOffset = value;
  53216. this._disposeBlurPostProcesses();
  53217. },
  53218. enumerable: true,
  53219. configurable: true
  53220. });
  53221. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  53222. get: function () {
  53223. return this._blurScale;
  53224. },
  53225. set: function (value) {
  53226. if (this._blurScale === value) {
  53227. return;
  53228. }
  53229. this._blurScale = value;
  53230. this._disposeBlurPostProcesses();
  53231. },
  53232. enumerable: true,
  53233. configurable: true
  53234. });
  53235. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  53236. get: function () {
  53237. return this._blurKernel;
  53238. },
  53239. set: function (value) {
  53240. if (this._blurKernel === value) {
  53241. return;
  53242. }
  53243. this._blurKernel = value;
  53244. this._disposeBlurPostProcesses();
  53245. },
  53246. enumerable: true,
  53247. configurable: true
  53248. });
  53249. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  53250. get: function () {
  53251. return this._useKernelBlur;
  53252. },
  53253. set: function (value) {
  53254. if (this._useKernelBlur === value) {
  53255. return;
  53256. }
  53257. this._useKernelBlur = value;
  53258. this._disposeBlurPostProcesses();
  53259. },
  53260. enumerable: true,
  53261. configurable: true
  53262. });
  53263. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  53264. get: function () {
  53265. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  53266. },
  53267. set: function (value) {
  53268. this._depthScale = value;
  53269. },
  53270. enumerable: true,
  53271. configurable: true
  53272. });
  53273. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  53274. get: function () {
  53275. return this._filter;
  53276. },
  53277. set: function (value) {
  53278. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  53279. if (this._light.needCube()) {
  53280. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  53281. this.useExponentialShadowMap = true;
  53282. return;
  53283. }
  53284. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  53285. this.useCloseExponentialShadowMap = true;
  53286. return;
  53287. }
  53288. }
  53289. if (this._filter === value) {
  53290. return;
  53291. }
  53292. this._filter = value;
  53293. this._disposeBlurPostProcesses();
  53294. this._applyFilterValues();
  53295. this._light._markMeshesAsLightDirty();
  53296. },
  53297. enumerable: true,
  53298. configurable: true
  53299. });
  53300. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  53301. get: function () {
  53302. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  53303. },
  53304. set: function (value) {
  53305. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  53306. return;
  53307. }
  53308. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  53309. },
  53310. enumerable: true,
  53311. configurable: true
  53312. });
  53313. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  53314. get: function () {
  53315. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  53316. return this.useExponentialShadowMap;
  53317. },
  53318. set: function (value) {
  53319. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  53320. this.useExponentialShadowMap = value;
  53321. },
  53322. enumerable: true,
  53323. configurable: true
  53324. });
  53325. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  53326. get: function () {
  53327. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  53328. return this.useBlurExponentialShadowMap;
  53329. },
  53330. set: function (value) {
  53331. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  53332. this.useBlurExponentialShadowMap = value;
  53333. },
  53334. enumerable: true,
  53335. configurable: true
  53336. });
  53337. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  53338. get: function () {
  53339. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  53340. },
  53341. set: function (value) {
  53342. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  53343. return;
  53344. }
  53345. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  53346. },
  53347. enumerable: true,
  53348. configurable: true
  53349. });
  53350. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  53351. get: function () {
  53352. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  53353. },
  53354. set: function (value) {
  53355. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  53356. return;
  53357. }
  53358. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  53359. },
  53360. enumerable: true,
  53361. configurable: true
  53362. });
  53363. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  53364. get: function () {
  53365. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  53366. },
  53367. set: function (value) {
  53368. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  53369. return;
  53370. }
  53371. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  53372. },
  53373. enumerable: true,
  53374. configurable: true
  53375. });
  53376. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  53377. get: function () {
  53378. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  53379. },
  53380. set: function (value) {
  53381. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  53382. return;
  53383. }
  53384. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  53385. },
  53386. enumerable: true,
  53387. configurable: true
  53388. });
  53389. /**
  53390. * Returns the darkness value (float).
  53391. */
  53392. ShadowGenerator.prototype.getDarkness = function () {
  53393. return this._darkness;
  53394. };
  53395. /**
  53396. * Sets the ShadowGenerator darkness value (float <= 1.0).
  53397. * Returns the ShadowGenerator.
  53398. */
  53399. ShadowGenerator.prototype.setDarkness = function (darkness) {
  53400. if (darkness >= 1.0)
  53401. this._darkness = 1.0;
  53402. else if (darkness <= 0.0)
  53403. this._darkness = 0.0;
  53404. else
  53405. this._darkness = darkness;
  53406. return this;
  53407. };
  53408. /**
  53409. * Sets the ability to have transparent shadow (boolean).
  53410. * Returns the ShadowGenerator.
  53411. */
  53412. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  53413. this._transparencyShadow = hasShadow;
  53414. return this;
  53415. };
  53416. /**
  53417. * Returns a RenderTargetTexture object : the shadow map texture.
  53418. */
  53419. ShadowGenerator.prototype.getShadowMap = function () {
  53420. return this._shadowMap;
  53421. };
  53422. /**
  53423. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  53424. */
  53425. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  53426. if (this._shadowMap2) {
  53427. return this._shadowMap2;
  53428. }
  53429. return this._shadowMap;
  53430. };
  53431. /**
  53432. * Helper function to add a mesh and its descendants to the list of shadow casters
  53433. * @param mesh Mesh to add
  53434. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  53435. */
  53436. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  53437. if (includeDescendants === void 0) { includeDescendants = true; }
  53438. if (!this._shadowMap) {
  53439. return this;
  53440. }
  53441. if (!this._shadowMap.renderList) {
  53442. this._shadowMap.renderList = [];
  53443. }
  53444. this._shadowMap.renderList.push(mesh);
  53445. if (includeDescendants) {
  53446. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  53447. }
  53448. return this;
  53449. var _a;
  53450. };
  53451. /**
  53452. * Helper function to remove a mesh and its descendants from the list of shadow casters
  53453. * @param mesh Mesh to remove
  53454. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  53455. */
  53456. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  53457. if (includeDescendants === void 0) { includeDescendants = true; }
  53458. if (!this._shadowMap || !this._shadowMap.renderList) {
  53459. return this;
  53460. }
  53461. var index = this._shadowMap.renderList.indexOf(mesh);
  53462. if (index !== -1) {
  53463. this._shadowMap.renderList.splice(index, 1);
  53464. }
  53465. if (includeDescendants) {
  53466. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  53467. var child = _a[_i];
  53468. this.removeShadowCaster(child);
  53469. }
  53470. }
  53471. return this;
  53472. };
  53473. /**
  53474. * Returns the associated light object.
  53475. */
  53476. ShadowGenerator.prototype.getLight = function () {
  53477. return this._light;
  53478. };
  53479. ShadowGenerator.prototype._initializeGenerator = function () {
  53480. this._light._markMeshesAsLightDirty();
  53481. this._initializeShadowMap();
  53482. };
  53483. ShadowGenerator.prototype._initializeShadowMap = function () {
  53484. var _this = this;
  53485. // Render target
  53486. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  53487. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53488. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53489. this._shadowMap.anisotropicFilteringLevel = 1;
  53490. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  53491. this._shadowMap.renderParticles = false;
  53492. this._shadowMap.ignoreCameraViewport = true;
  53493. // Record Face Index before render.
  53494. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  53495. _this._currentFaceIndex = faceIndex;
  53496. });
  53497. // Custom render function.
  53498. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  53499. // Blur if required afer render.
  53500. this._shadowMap.onAfterUnbindObservable.add(function () {
  53501. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  53502. return;
  53503. }
  53504. if (!_this._blurPostProcesses || !_this._blurPostProcesses.length) {
  53505. _this._initializeBlurRTTAndPostProcesses();
  53506. }
  53507. var shadowMap = _this.getShadowMapForRendering();
  53508. if (shadowMap) {
  53509. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  53510. }
  53511. });
  53512. // Clear according to the chosen filter.
  53513. this._shadowMap.onClearObservable.add(function (engine) {
  53514. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  53515. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  53516. }
  53517. else {
  53518. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  53519. }
  53520. });
  53521. };
  53522. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  53523. var _this = this;
  53524. var engine = this._scene.getEngine();
  53525. var targetSize = this._mapSize / this.blurScale;
  53526. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  53527. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  53528. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53529. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53530. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  53531. }
  53532. if (this.useKernelBlur) {
  53533. 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);
  53534. this._kernelBlurXPostprocess.width = targetSize;
  53535. this._kernelBlurXPostprocess.height = targetSize;
  53536. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  53537. effect.setTexture("textureSampler", _this._shadowMap);
  53538. });
  53539. 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);
  53540. this._kernelBlurXPostprocess.autoClear = false;
  53541. this._kernelBlurYPostprocess.autoClear = false;
  53542. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  53543. this._kernelBlurXPostprocess.packedFloat = true;
  53544. this._kernelBlurYPostprocess.packedFloat = true;
  53545. }
  53546. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  53547. }
  53548. else {
  53549. 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);
  53550. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  53551. effect.setFloat2("screenSize", targetSize, targetSize);
  53552. effect.setTexture("textureSampler", _this._shadowMap);
  53553. });
  53554. this._boxBlurPostprocess.autoClear = false;
  53555. this._blurPostProcesses = [this._boxBlurPostprocess];
  53556. }
  53557. };
  53558. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  53559. var index;
  53560. var engine = this._scene.getEngine();
  53561. if (depthOnlySubMeshes.length) {
  53562. engine.setColorWrite(false);
  53563. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  53564. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  53565. }
  53566. engine.setColorWrite(true);
  53567. }
  53568. for (index = 0; index < opaqueSubMeshes.length; index++) {
  53569. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  53570. }
  53571. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  53572. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  53573. }
  53574. if (this._transparencyShadow) {
  53575. for (index = 0; index < transparentSubMeshes.length; index++) {
  53576. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  53577. }
  53578. }
  53579. };
  53580. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  53581. var _this = this;
  53582. var mesh = subMesh.getRenderingMesh();
  53583. var scene = this._scene;
  53584. var engine = scene.getEngine();
  53585. var material = subMesh.getMaterial();
  53586. if (!material) {
  53587. return;
  53588. }
  53589. // Culling
  53590. engine.setState(material.backFaceCulling);
  53591. // Managing instances
  53592. var batch = mesh._getInstancesRenderList(subMesh._id);
  53593. if (batch.mustReturn) {
  53594. return;
  53595. }
  53596. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  53597. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  53598. engine.enableEffect(this._effect);
  53599. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  53600. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  53601. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  53602. this._effect.setVector3("lightPosition", this.getLight().position);
  53603. if (scene.activeCamera) {
  53604. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  53605. }
  53606. // Alpha test
  53607. if (material && material.needAlphaTesting()) {
  53608. var alphaTexture = material.getAlphaTestTexture();
  53609. if (alphaTexture) {
  53610. this._effect.setTexture("diffuseSampler", alphaTexture);
  53611. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  53612. }
  53613. }
  53614. // Bones
  53615. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53616. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  53617. }
  53618. if (this.forceBackFacesOnly) {
  53619. engine.setState(true, 0, false, true);
  53620. }
  53621. // Draw
  53622. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  53623. if (this.forceBackFacesOnly) {
  53624. engine.setState(true, 0, false, false);
  53625. }
  53626. }
  53627. else {
  53628. // Need to reset refresh rate of the shadowMap
  53629. if (this._shadowMap) {
  53630. this._shadowMap.resetRefreshCounter();
  53631. }
  53632. }
  53633. };
  53634. ShadowGenerator.prototype._applyFilterValues = function () {
  53635. if (!this._shadowMap) {
  53636. return;
  53637. }
  53638. if (this.filter === ShadowGenerator.FILTER_NONE) {
  53639. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  53640. }
  53641. else {
  53642. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  53643. }
  53644. };
  53645. /**
  53646. * Force shader compilation including textures ready check
  53647. */
  53648. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  53649. var _this = this;
  53650. var localOptions = __assign({ useInstances: false }, options);
  53651. var shadowMap = this.getShadowMap();
  53652. if (!shadowMap) {
  53653. if (onCompiled) {
  53654. onCompiled(this);
  53655. }
  53656. return;
  53657. }
  53658. var renderList = shadowMap.renderList;
  53659. if (!renderList) {
  53660. if (onCompiled) {
  53661. onCompiled(this);
  53662. }
  53663. return;
  53664. }
  53665. var subMeshes = new Array();
  53666. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  53667. var mesh = renderList_1[_i];
  53668. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  53669. }
  53670. if (subMeshes.length === 0) {
  53671. if (onCompiled) {
  53672. onCompiled(this);
  53673. }
  53674. return;
  53675. }
  53676. var currentIndex = 0;
  53677. var checkReady = function () {
  53678. if (!_this._scene || !_this._scene.getEngine()) {
  53679. return;
  53680. }
  53681. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  53682. currentIndex++;
  53683. if (currentIndex >= subMeshes.length) {
  53684. if (onCompiled) {
  53685. onCompiled(_this);
  53686. }
  53687. return;
  53688. }
  53689. }
  53690. setTimeout(checkReady, 16);
  53691. };
  53692. checkReady();
  53693. };
  53694. /**
  53695. * Boolean : true when the ShadowGenerator is finally computed.
  53696. */
  53697. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  53698. var defines = [];
  53699. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  53700. defines.push("#define FLOAT");
  53701. }
  53702. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  53703. defines.push("#define ESM");
  53704. }
  53705. var attribs = [BABYLON.VertexBuffer.PositionKind];
  53706. var mesh = subMesh.getMesh();
  53707. var material = subMesh.getMaterial();
  53708. // Alpha test
  53709. if (material && material.needAlphaTesting()) {
  53710. var alphaTexture = material.getAlphaTestTexture();
  53711. if (alphaTexture) {
  53712. defines.push("#define ALPHATEST");
  53713. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53714. attribs.push(BABYLON.VertexBuffer.UVKind);
  53715. defines.push("#define UV1");
  53716. }
  53717. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  53718. if (alphaTexture.coordinatesIndex === 1) {
  53719. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  53720. defines.push("#define UV2");
  53721. }
  53722. }
  53723. }
  53724. }
  53725. // Bones
  53726. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53727. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53728. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53729. if (mesh.numBoneInfluencers > 4) {
  53730. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  53731. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  53732. }
  53733. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53734. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53735. }
  53736. else {
  53737. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53738. }
  53739. // Instances
  53740. if (useInstances) {
  53741. defines.push("#define INSTANCES");
  53742. attribs.push("world0");
  53743. attribs.push("world1");
  53744. attribs.push("world2");
  53745. attribs.push("world3");
  53746. }
  53747. // Get correct effect
  53748. var join = defines.join("\n");
  53749. if (this._cachedDefines !== join) {
  53750. this._cachedDefines = join;
  53751. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  53752. }
  53753. return this._effect.isReady();
  53754. };
  53755. /**
  53756. * This creates the defines related to the standard BJS materials.
  53757. */
  53758. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  53759. var scene = this._scene;
  53760. var light = this._light;
  53761. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  53762. return;
  53763. }
  53764. defines["SHADOW" + lightIndex] = true;
  53765. if (this.usePoissonSampling) {
  53766. defines["SHADOWPCF" + lightIndex] = true;
  53767. }
  53768. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  53769. defines["SHADOWESM" + lightIndex] = true;
  53770. }
  53771. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  53772. defines["SHADOWCLOSEESM" + lightIndex] = true;
  53773. }
  53774. if (light.needCube()) {
  53775. defines["SHADOWCUBE" + lightIndex] = true;
  53776. }
  53777. };
  53778. /**
  53779. * This binds shadow lights related to the standard BJS materials.
  53780. * It implies the unifroms available on the materials are the standard BJS ones.
  53781. */
  53782. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  53783. var light = this._light;
  53784. var scene = this._scene;
  53785. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  53786. return;
  53787. }
  53788. var camera = scene.activeCamera;
  53789. if (!camera) {
  53790. return;
  53791. }
  53792. var shadowMap = this.getShadowMap();
  53793. if (!shadowMap) {
  53794. return;
  53795. }
  53796. if (!light.needCube()) {
  53797. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  53798. }
  53799. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  53800. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  53801. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  53802. };
  53803. // Methods
  53804. /**
  53805. * Returns a Matrix object : the updated transformation matrix.
  53806. */
  53807. ShadowGenerator.prototype.getTransformMatrix = function () {
  53808. var scene = this._scene;
  53809. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  53810. return this._transformMatrix;
  53811. }
  53812. this._currentRenderID = scene.getRenderId();
  53813. this._currentFaceIndexCache = this._currentFaceIndex;
  53814. var lightPosition = this._light.position;
  53815. if (this._light.computeTransformedInformation()) {
  53816. lightPosition = this._light.transformedPosition;
  53817. }
  53818. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  53819. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  53820. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  53821. }
  53822. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  53823. this._cachedPosition = lightPosition.clone();
  53824. this._cachedDirection = this._lightDirection.clone();
  53825. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  53826. var shadowMap = this.getShadowMap();
  53827. if (shadowMap) {
  53828. var renderList = shadowMap.renderList;
  53829. if (renderList) {
  53830. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  53831. }
  53832. }
  53833. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  53834. }
  53835. return this._transformMatrix;
  53836. };
  53837. ShadowGenerator.prototype.recreateShadowMap = function () {
  53838. var shadowMap = this._shadowMap;
  53839. if (!shadowMap) {
  53840. return;
  53841. }
  53842. // Track render list.
  53843. var renderList = shadowMap.renderList;
  53844. // Clean up existing data.
  53845. this._disposeRTTandPostProcesses();
  53846. // Reinitializes.
  53847. this._initializeGenerator();
  53848. // Reaffect the filter to ensure a correct fallback if necessary.
  53849. this.filter = this.filter;
  53850. // Reaffect the filter.
  53851. this._applyFilterValues();
  53852. // Reaffect Render List.
  53853. this._shadowMap.renderList = renderList;
  53854. };
  53855. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  53856. if (this._shadowMap2) {
  53857. this._shadowMap2.dispose();
  53858. this._shadowMap2 = null;
  53859. }
  53860. if (this._downSamplePostprocess) {
  53861. this._downSamplePostprocess.dispose();
  53862. this._downSamplePostprocess = null;
  53863. }
  53864. if (this._boxBlurPostprocess) {
  53865. this._boxBlurPostprocess.dispose();
  53866. this._boxBlurPostprocess = null;
  53867. }
  53868. if (this._kernelBlurXPostprocess) {
  53869. this._kernelBlurXPostprocess.dispose();
  53870. this._kernelBlurXPostprocess = null;
  53871. }
  53872. if (this._kernelBlurYPostprocess) {
  53873. this._kernelBlurYPostprocess.dispose();
  53874. this._kernelBlurYPostprocess = null;
  53875. }
  53876. this._blurPostProcesses = [];
  53877. };
  53878. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  53879. if (this._shadowMap) {
  53880. this._shadowMap.dispose();
  53881. this._shadowMap = null;
  53882. }
  53883. this._disposeBlurPostProcesses();
  53884. };
  53885. /**
  53886. * Disposes the ShadowGenerator.
  53887. * Returns nothing.
  53888. */
  53889. ShadowGenerator.prototype.dispose = function () {
  53890. this._disposeRTTandPostProcesses();
  53891. if (this._light) {
  53892. this._light._shadowGenerator = null;
  53893. this._light._markMeshesAsLightDirty();
  53894. }
  53895. };
  53896. /**
  53897. * Serializes the ShadowGenerator and returns a serializationObject.
  53898. */
  53899. ShadowGenerator.prototype.serialize = function () {
  53900. var serializationObject = {};
  53901. var shadowMap = this.getShadowMap();
  53902. if (!shadowMap) {
  53903. return serializationObject;
  53904. }
  53905. serializationObject.lightId = this._light.id;
  53906. serializationObject.mapSize = shadowMap.getRenderSize();
  53907. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  53908. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  53909. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  53910. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  53911. serializationObject.usePoissonSampling = this.usePoissonSampling;
  53912. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  53913. serializationObject.depthScale = this.depthScale;
  53914. serializationObject.darkness = this.getDarkness();
  53915. serializationObject.blurBoxOffset = this.blurBoxOffset;
  53916. serializationObject.blurKernel = this.blurKernel;
  53917. serializationObject.blurScale = this.blurScale;
  53918. serializationObject.useKernelBlur = this.useKernelBlur;
  53919. serializationObject.transparencyShadow = this._transparencyShadow;
  53920. serializationObject.renderList = [];
  53921. if (shadowMap.renderList) {
  53922. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  53923. var mesh = shadowMap.renderList[meshIndex];
  53924. serializationObject.renderList.push(mesh.id);
  53925. }
  53926. }
  53927. return serializationObject;
  53928. };
  53929. /**
  53930. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  53931. */
  53932. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  53933. //casting to point light, as light is missing the position attr and typescript complains.
  53934. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  53935. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  53936. var shadowMap = shadowGenerator.getShadowMap();
  53937. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  53938. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  53939. meshes.forEach(function (mesh) {
  53940. if (!shadowMap) {
  53941. return;
  53942. }
  53943. if (!shadowMap.renderList) {
  53944. shadowMap.renderList = [];
  53945. }
  53946. shadowMap.renderList.push(mesh);
  53947. });
  53948. }
  53949. if (parsedShadowGenerator.usePoissonSampling) {
  53950. shadowGenerator.usePoissonSampling = true;
  53951. }
  53952. else if (parsedShadowGenerator.useExponentialShadowMap) {
  53953. shadowGenerator.useExponentialShadowMap = true;
  53954. }
  53955. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  53956. shadowGenerator.useBlurExponentialShadowMap = true;
  53957. }
  53958. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  53959. shadowGenerator.useCloseExponentialShadowMap = true;
  53960. }
  53961. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  53962. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  53963. }
  53964. else if (parsedShadowGenerator.useVarianceShadowMap) {
  53965. shadowGenerator.useExponentialShadowMap = true;
  53966. }
  53967. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  53968. shadowGenerator.useBlurExponentialShadowMap = true;
  53969. }
  53970. if (parsedShadowGenerator.depthScale) {
  53971. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  53972. }
  53973. if (parsedShadowGenerator.blurScale) {
  53974. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  53975. }
  53976. if (parsedShadowGenerator.blurBoxOffset) {
  53977. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  53978. }
  53979. if (parsedShadowGenerator.useKernelBlur) {
  53980. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  53981. }
  53982. if (parsedShadowGenerator.blurKernel) {
  53983. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  53984. }
  53985. if (parsedShadowGenerator.bias !== undefined) {
  53986. shadowGenerator.bias = parsedShadowGenerator.bias;
  53987. }
  53988. if (parsedShadowGenerator.darkness) {
  53989. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  53990. }
  53991. if (parsedShadowGenerator.transparencyShadow) {
  53992. shadowGenerator.setTransparencyShadow(true);
  53993. }
  53994. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  53995. return shadowGenerator;
  53996. };
  53997. ShadowGenerator._FILTER_NONE = 0;
  53998. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  53999. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  54000. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  54001. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  54002. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  54003. return ShadowGenerator;
  54004. }());
  54005. BABYLON.ShadowGenerator = ShadowGenerator;
  54006. })(BABYLON || (BABYLON = {}));
  54007. //# sourceMappingURL=babylon.shadowGenerator.js.map
  54008. var BABYLON;
  54009. (function (BABYLON) {
  54010. var DefaultLoadingScreen = /** @class */ (function () {
  54011. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  54012. if (_loadingText === void 0) { _loadingText = ""; }
  54013. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  54014. var _this = this;
  54015. this._renderingCanvas = _renderingCanvas;
  54016. this._loadingText = _loadingText;
  54017. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  54018. // Resize
  54019. this._resizeLoadingUI = function () {
  54020. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  54021. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  54022. if (!_this._loadingDiv) {
  54023. return;
  54024. }
  54025. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  54026. _this._loadingDiv.style.left = canvasRect.left + "px";
  54027. _this._loadingDiv.style.top = canvasRect.top + "px";
  54028. _this._loadingDiv.style.width = canvasRect.width + "px";
  54029. _this._loadingDiv.style.height = canvasRect.height + "px";
  54030. };
  54031. }
  54032. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  54033. if (this._loadingDiv) {
  54034. // Do not add a loading screen if there is already one
  54035. return;
  54036. }
  54037. this._loadingDiv = document.createElement("div");
  54038. this._loadingDiv.id = "babylonjsLoadingDiv";
  54039. this._loadingDiv.style.opacity = "0";
  54040. this._loadingDiv.style.transition = "opacity 1.5s ease";
  54041. this._loadingDiv.style.pointerEvents = "none";
  54042. // Loading text
  54043. this._loadingTextDiv = document.createElement("div");
  54044. this._loadingTextDiv.style.position = "absolute";
  54045. this._loadingTextDiv.style.left = "0";
  54046. this._loadingTextDiv.style.top = "50%";
  54047. this._loadingTextDiv.style.marginTop = "80px";
  54048. this._loadingTextDiv.style.width = "100%";
  54049. this._loadingTextDiv.style.height = "20px";
  54050. this._loadingTextDiv.style.fontFamily = "Arial";
  54051. this._loadingTextDiv.style.fontSize = "14px";
  54052. this._loadingTextDiv.style.color = "white";
  54053. this._loadingTextDiv.style.textAlign = "center";
  54054. this._loadingTextDiv.innerHTML = "Loading";
  54055. this._loadingDiv.appendChild(this._loadingTextDiv);
  54056. //set the predefined text
  54057. this._loadingTextDiv.innerHTML = this._loadingText;
  54058. // Generating keyframes
  54059. var style = document.createElement('style');
  54060. style.type = 'text/css';
  54061. 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 }";
  54062. style.innerHTML = keyFrames;
  54063. document.getElementsByTagName('head')[0].appendChild(style);
  54064. // Loading img
  54065. var imgBack = new Image();
  54066. 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";
  54067. imgBack.style.position = "absolute";
  54068. imgBack.style.left = "50%";
  54069. imgBack.style.top = "50%";
  54070. imgBack.style.marginLeft = "-60px";
  54071. imgBack.style.marginTop = "-60px";
  54072. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  54073. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  54074. imgBack.style.transformOrigin = "50% 50%";
  54075. imgBack.style.webkitTransformOrigin = "50% 50%";
  54076. this._loadingDiv.appendChild(imgBack);
  54077. this._resizeLoadingUI();
  54078. window.addEventListener("resize", this._resizeLoadingUI);
  54079. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  54080. document.body.appendChild(this._loadingDiv);
  54081. this._loadingDiv.style.opacity = "1";
  54082. };
  54083. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  54084. var _this = this;
  54085. if (!this._loadingDiv) {
  54086. return;
  54087. }
  54088. var onTransitionEnd = function () {
  54089. if (!_this._loadingDiv) {
  54090. return;
  54091. }
  54092. document.body.removeChild(_this._loadingDiv);
  54093. window.removeEventListener("resize", _this._resizeLoadingUI);
  54094. _this._loadingDiv = null;
  54095. };
  54096. this._loadingDiv.style.opacity = "0";
  54097. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  54098. };
  54099. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  54100. set: function (text) {
  54101. this._loadingText = text;
  54102. if (this._loadingTextDiv) {
  54103. this._loadingTextDiv.innerHTML = this._loadingText;
  54104. }
  54105. },
  54106. enumerable: true,
  54107. configurable: true
  54108. });
  54109. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  54110. get: function () {
  54111. return this._loadingDivBackgroundColor;
  54112. },
  54113. set: function (color) {
  54114. this._loadingDivBackgroundColor = color;
  54115. if (!this._loadingDiv) {
  54116. return;
  54117. }
  54118. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  54119. },
  54120. enumerable: true,
  54121. configurable: true
  54122. });
  54123. return DefaultLoadingScreen;
  54124. }());
  54125. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  54126. })(BABYLON || (BABYLON = {}));
  54127. //# sourceMappingURL=babylon.loadingScreen.js.map
  54128. var BABYLON;
  54129. (function (BABYLON) {
  54130. var SceneLoaderProgressEvent = /** @class */ (function () {
  54131. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  54132. this.lengthComputable = lengthComputable;
  54133. this.loaded = loaded;
  54134. this.total = total;
  54135. }
  54136. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  54137. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  54138. };
  54139. return SceneLoaderProgressEvent;
  54140. }());
  54141. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  54142. var SceneLoader = /** @class */ (function () {
  54143. function SceneLoader() {
  54144. }
  54145. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  54146. get: function () {
  54147. return 0;
  54148. },
  54149. enumerable: true,
  54150. configurable: true
  54151. });
  54152. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  54153. get: function () {
  54154. return 1;
  54155. },
  54156. enumerable: true,
  54157. configurable: true
  54158. });
  54159. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  54160. get: function () {
  54161. return 2;
  54162. },
  54163. enumerable: true,
  54164. configurable: true
  54165. });
  54166. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  54167. get: function () {
  54168. return 3;
  54169. },
  54170. enumerable: true,
  54171. configurable: true
  54172. });
  54173. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  54174. get: function () {
  54175. return SceneLoader._ForceFullSceneLoadingForIncremental;
  54176. },
  54177. set: function (value) {
  54178. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  54179. },
  54180. enumerable: true,
  54181. configurable: true
  54182. });
  54183. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  54184. get: function () {
  54185. return SceneLoader._ShowLoadingScreen;
  54186. },
  54187. set: function (value) {
  54188. SceneLoader._ShowLoadingScreen = value;
  54189. },
  54190. enumerable: true,
  54191. configurable: true
  54192. });
  54193. Object.defineProperty(SceneLoader, "loggingLevel", {
  54194. get: function () {
  54195. return SceneLoader._loggingLevel;
  54196. },
  54197. set: function (value) {
  54198. SceneLoader._loggingLevel = value;
  54199. },
  54200. enumerable: true,
  54201. configurable: true
  54202. });
  54203. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  54204. get: function () {
  54205. return SceneLoader._CleanBoneMatrixWeights;
  54206. },
  54207. set: function (value) {
  54208. SceneLoader._CleanBoneMatrixWeights = value;
  54209. },
  54210. enumerable: true,
  54211. configurable: true
  54212. });
  54213. SceneLoader._getDefaultPlugin = function () {
  54214. return SceneLoader._registeredPlugins[".babylon"];
  54215. };
  54216. SceneLoader._getPluginForExtension = function (extension) {
  54217. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  54218. if (registeredPlugin) {
  54219. return registeredPlugin;
  54220. }
  54221. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  54222. return SceneLoader._getDefaultPlugin();
  54223. };
  54224. SceneLoader._getPluginForDirectLoad = function (data) {
  54225. for (var extension in SceneLoader._registeredPlugins) {
  54226. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  54227. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  54228. return SceneLoader._registeredPlugins[extension];
  54229. }
  54230. }
  54231. return SceneLoader._getDefaultPlugin();
  54232. };
  54233. SceneLoader._getPluginForFilename = function (sceneFilename) {
  54234. if (sceneFilename.name) {
  54235. sceneFilename = sceneFilename.name;
  54236. }
  54237. var queryStringPosition = sceneFilename.indexOf("?");
  54238. if (queryStringPosition !== -1) {
  54239. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  54240. }
  54241. var dotPosition = sceneFilename.lastIndexOf(".");
  54242. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  54243. return SceneLoader._getPluginForExtension(extension);
  54244. };
  54245. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  54246. SceneLoader._getDirectLoad = function (sceneFilename) {
  54247. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  54248. return sceneFilename.substr(5);
  54249. }
  54250. return null;
  54251. };
  54252. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  54253. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  54254. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  54255. var plugin;
  54256. if (registeredPlugin.plugin.createPlugin) {
  54257. plugin = registeredPlugin.plugin.createPlugin();
  54258. }
  54259. else {
  54260. plugin = registeredPlugin.plugin;
  54261. }
  54262. var useArrayBuffer = registeredPlugin.isBinary;
  54263. var database;
  54264. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  54265. var dataCallback = function (data, responseURL) {
  54266. if (scene.isDisposed) {
  54267. onError("Scene has been disposed");
  54268. return;
  54269. }
  54270. scene.database = database;
  54271. onSuccess(plugin, data, responseURL);
  54272. };
  54273. var request = null;
  54274. var pluginDisposed = false;
  54275. var onDisposeObservable = plugin.onDisposeObservable;
  54276. if (onDisposeObservable) {
  54277. onDisposeObservable.add(function () {
  54278. pluginDisposed = true;
  54279. if (request) {
  54280. request.abort();
  54281. request = null;
  54282. }
  54283. onDispose();
  54284. });
  54285. }
  54286. var manifestChecked = function () {
  54287. if (pluginDisposed) {
  54288. return;
  54289. }
  54290. var url = rootUrl + sceneFilename;
  54291. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  54292. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  54293. } : undefined, database, useArrayBuffer, function (request, exception) {
  54294. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  54295. });
  54296. };
  54297. if (directLoad) {
  54298. dataCallback(directLoad);
  54299. return plugin;
  54300. }
  54301. if (rootUrl.indexOf("file:") === -1) {
  54302. if (scene.getEngine().enableOfflineSupport) {
  54303. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  54304. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  54305. }
  54306. else {
  54307. manifestChecked();
  54308. }
  54309. }
  54310. else {
  54311. var fileOrString = sceneFilename;
  54312. if (fileOrString.name) {
  54313. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  54314. }
  54315. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  54316. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  54317. }
  54318. else {
  54319. onError("Unable to find file named " + sceneFilename);
  54320. }
  54321. }
  54322. return plugin;
  54323. };
  54324. // Public functions
  54325. SceneLoader.GetPluginForExtension = function (extension) {
  54326. return SceneLoader._getPluginForExtension(extension).plugin;
  54327. };
  54328. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  54329. return !!SceneLoader._registeredPlugins[extension];
  54330. };
  54331. SceneLoader.RegisterPlugin = function (plugin) {
  54332. if (typeof plugin.extensions === "string") {
  54333. var extension = plugin.extensions;
  54334. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  54335. plugin: plugin,
  54336. isBinary: false
  54337. };
  54338. }
  54339. else {
  54340. var extensions = plugin.extensions;
  54341. Object.keys(extensions).forEach(function (extension) {
  54342. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  54343. plugin: plugin,
  54344. isBinary: extensions[extension].isBinary
  54345. };
  54346. });
  54347. }
  54348. };
  54349. /**
  54350. * Import meshes into a scene
  54351. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  54352. * @param rootUrl a string that defines the root url for scene and resources
  54353. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  54354. * @param scene the instance of BABYLON.Scene to append to
  54355. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  54356. * @param onProgress a callback with a progress event for each file being loaded
  54357. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  54358. */
  54359. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  54360. if (onSuccess === void 0) { onSuccess = null; }
  54361. if (onProgress === void 0) { onProgress = null; }
  54362. if (onError === void 0) { onError = null; }
  54363. if (pluginExtension === void 0) { pluginExtension = null; }
  54364. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  54365. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  54366. return null;
  54367. }
  54368. var loadingToken = {};
  54369. scene._addPendingData(loadingToken);
  54370. var disposeHandler = function () {
  54371. scene._removePendingData(loadingToken);
  54372. };
  54373. var errorHandler = function (message, exception) {
  54374. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  54375. if (onError) {
  54376. onError(scene, errorMessage, exception);
  54377. }
  54378. else {
  54379. BABYLON.Tools.Error(errorMessage);
  54380. // should the exception be thrown?
  54381. }
  54382. disposeHandler();
  54383. };
  54384. var progressHandler = onProgress ? function (event) {
  54385. try {
  54386. onProgress(event);
  54387. }
  54388. catch (e) {
  54389. errorHandler("Error in onProgress callback", e);
  54390. }
  54391. } : undefined;
  54392. var successHandler = function (meshes, particleSystems, skeletons) {
  54393. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  54394. if (onSuccess) {
  54395. try {
  54396. onSuccess(meshes, particleSystems, skeletons);
  54397. }
  54398. catch (e) {
  54399. errorHandler("Error in onSuccess callback", e);
  54400. }
  54401. }
  54402. scene._removePendingData(loadingToken);
  54403. };
  54404. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  54405. if (plugin.rewriteRootURL) {
  54406. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  54407. }
  54408. if (plugin.importMesh) {
  54409. var syncedPlugin = plugin;
  54410. var meshes = new Array();
  54411. var particleSystems = new Array();
  54412. var skeletons = new Array();
  54413. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  54414. return;
  54415. }
  54416. scene.loadingPluginName = plugin.name;
  54417. successHandler(meshes, particleSystems, skeletons);
  54418. }
  54419. else {
  54420. var asyncedPlugin = plugin;
  54421. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  54422. scene.loadingPluginName = plugin.name;
  54423. successHandler(meshes, particleSystems, skeletons);
  54424. }, progressHandler, errorHandler);
  54425. }
  54426. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  54427. };
  54428. /**
  54429. * Load a scene
  54430. * @param rootUrl a string that defines the root url for scene and resources
  54431. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  54432. * @param engine is the instance of BABYLON.Engine to use to create the scene
  54433. * @param onSuccess a callback with the scene when import succeeds
  54434. * @param onProgress a callback with a progress event for each file being loaded
  54435. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  54436. */
  54437. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  54438. if (onSuccess === void 0) { onSuccess = null; }
  54439. if (onProgress === void 0) { onProgress = null; }
  54440. if (onError === void 0) { onError = null; }
  54441. if (pluginExtension === void 0) { pluginExtension = null; }
  54442. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  54443. };
  54444. /**
  54445. * Append a scene
  54446. * @param rootUrl a string that defines the root url for scene and resources
  54447. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  54448. * @param scene is the instance of BABYLON.Scene to append to
  54449. * @param onSuccess a callback with the scene when import succeeds
  54450. * @param onProgress a callback with a progress event for each file being loaded
  54451. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  54452. */
  54453. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  54454. if (onSuccess === void 0) { onSuccess = null; }
  54455. if (onProgress === void 0) { onProgress = null; }
  54456. if (onError === void 0) { onError = null; }
  54457. if (pluginExtension === void 0) { pluginExtension = null; }
  54458. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  54459. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  54460. return null;
  54461. }
  54462. if (SceneLoader.ShowLoadingScreen) {
  54463. scene.getEngine().displayLoadingUI();
  54464. }
  54465. var loadingToken = {};
  54466. scene._addPendingData(loadingToken);
  54467. var disposeHandler = function () {
  54468. scene._removePendingData(loadingToken);
  54469. scene.getEngine().hideLoadingUI();
  54470. };
  54471. var errorHandler = function (message, exception) {
  54472. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  54473. if (onError) {
  54474. onError(scene, errorMessage, exception);
  54475. }
  54476. else {
  54477. BABYLON.Tools.Error(errorMessage);
  54478. // should the exception be thrown?
  54479. }
  54480. disposeHandler();
  54481. };
  54482. var progressHandler = onProgress ? function (event) {
  54483. try {
  54484. onProgress(event);
  54485. }
  54486. catch (e) {
  54487. errorHandler("Error in onProgress callback", e);
  54488. }
  54489. } : undefined;
  54490. var successHandler = function () {
  54491. if (onSuccess) {
  54492. try {
  54493. onSuccess(scene);
  54494. }
  54495. catch (e) {
  54496. errorHandler("Error in onSuccess callback", e);
  54497. }
  54498. }
  54499. scene._removePendingData(loadingToken);
  54500. };
  54501. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  54502. if (plugin.load) {
  54503. var syncedPlugin = plugin;
  54504. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  54505. return;
  54506. }
  54507. scene.loadingPluginName = plugin.name;
  54508. successHandler();
  54509. }
  54510. else {
  54511. var asyncedPlugin = plugin;
  54512. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  54513. scene.loadingPluginName = plugin.name;
  54514. successHandler();
  54515. }, progressHandler, errorHandler);
  54516. }
  54517. if (SceneLoader.ShowLoadingScreen) {
  54518. scene.executeWhenReady(function () {
  54519. scene.getEngine().hideLoadingUI();
  54520. });
  54521. }
  54522. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  54523. };
  54524. // Flags
  54525. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  54526. SceneLoader._ShowLoadingScreen = true;
  54527. SceneLoader._CleanBoneMatrixWeights = false;
  54528. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  54529. // Members
  54530. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  54531. SceneLoader._registeredPlugins = {};
  54532. return SceneLoader;
  54533. }());
  54534. BABYLON.SceneLoader = SceneLoader;
  54535. ;
  54536. })(BABYLON || (BABYLON = {}));
  54537. //# sourceMappingURL=babylon.sceneLoader.js.map
  54538. var BABYLON;
  54539. (function (BABYLON) {
  54540. var Internals;
  54541. (function (Internals) {
  54542. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  54543. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  54544. var parsedMaterial = parsedData.materials[index];
  54545. if (parsedMaterial.id === id) {
  54546. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  54547. }
  54548. }
  54549. return null;
  54550. };
  54551. var isDescendantOf = function (mesh, names, hierarchyIds) {
  54552. for (var i in names) {
  54553. if (mesh.name === names[i]) {
  54554. hierarchyIds.push(mesh.id);
  54555. return true;
  54556. }
  54557. }
  54558. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  54559. hierarchyIds.push(mesh.id);
  54560. return true;
  54561. }
  54562. return false;
  54563. };
  54564. var logOperation = function (operation, producer) {
  54565. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  54566. };
  54567. BABYLON.SceneLoader.RegisterPlugin({
  54568. name: "babylon.js",
  54569. extensions: ".babylon",
  54570. canDirectLoad: function (data) {
  54571. if (data.indexOf("babylon") !== -1) {
  54572. return true;
  54573. }
  54574. return false;
  54575. },
  54576. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  54577. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  54578. // when SceneLoader.debugLogging = true (default), or exception encountered.
  54579. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  54580. // and avoid problems with multiple concurrent .babylon loads.
  54581. var log = "importMesh has failed JSON parse";
  54582. try {
  54583. var parsedData = JSON.parse(data);
  54584. log = "";
  54585. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  54586. if (!meshesNames) {
  54587. meshesNames = null;
  54588. }
  54589. else if (!Array.isArray(meshesNames)) {
  54590. meshesNames = [meshesNames];
  54591. }
  54592. var hierarchyIds = new Array();
  54593. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  54594. var loadedSkeletonsIds = [];
  54595. var loadedMaterialsIds = [];
  54596. var index;
  54597. var cache;
  54598. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  54599. var parsedMesh = parsedData.meshes[index];
  54600. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  54601. if (meshesNames !== null) {
  54602. // Remove found mesh name from list.
  54603. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  54604. }
  54605. //Geometry?
  54606. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  54607. //does the file contain geometries?
  54608. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  54609. //find the correct geometry and add it to the scene
  54610. var found = false;
  54611. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  54612. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  54613. return;
  54614. }
  54615. else {
  54616. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  54617. if (parsedGeometryData.id === parsedMesh.geometryId) {
  54618. switch (geometryType) {
  54619. case "boxes":
  54620. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  54621. break;
  54622. case "spheres":
  54623. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  54624. break;
  54625. case "cylinders":
  54626. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  54627. break;
  54628. case "toruses":
  54629. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  54630. break;
  54631. case "grounds":
  54632. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  54633. break;
  54634. case "planes":
  54635. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  54636. break;
  54637. case "torusKnots":
  54638. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  54639. break;
  54640. case "vertexData":
  54641. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  54642. break;
  54643. }
  54644. found = true;
  54645. }
  54646. });
  54647. }
  54648. });
  54649. if (found === false) {
  54650. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  54651. }
  54652. }
  54653. }
  54654. // Material ?
  54655. if (parsedMesh.materialId) {
  54656. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  54657. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  54658. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  54659. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  54660. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  54661. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  54662. var subMatId = parsedMultiMaterial.materials[matIndex];
  54663. loadedMaterialsIds.push(subMatId);
  54664. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  54665. log += "\n\tMaterial " + mat.toString(fullDetails);
  54666. }
  54667. loadedMaterialsIds.push(parsedMultiMaterial.id);
  54668. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  54669. materialFound = true;
  54670. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  54671. break;
  54672. }
  54673. }
  54674. }
  54675. if (materialFound === false) {
  54676. loadedMaterialsIds.push(parsedMesh.materialId);
  54677. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  54678. if (!mat) {
  54679. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  54680. }
  54681. else {
  54682. log += "\n\tMaterial " + mat.toString(fullDetails);
  54683. }
  54684. }
  54685. }
  54686. // Skeleton ?
  54687. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  54688. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  54689. if (skeletonAlreadyLoaded === false) {
  54690. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  54691. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  54692. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  54693. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  54694. skeletons.push(skeleton);
  54695. loadedSkeletonsIds.push(parsedSkeleton.id);
  54696. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  54697. }
  54698. }
  54699. }
  54700. }
  54701. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  54702. meshes.push(mesh);
  54703. log += "\n\tMesh " + mesh.toString(fullDetails);
  54704. }
  54705. }
  54706. // Connecting parents
  54707. var currentMesh;
  54708. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  54709. currentMesh = scene.meshes[index];
  54710. if (currentMesh._waitingParentId) {
  54711. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  54712. currentMesh._waitingParentId = null;
  54713. }
  54714. }
  54715. // freeze and compute world matrix application
  54716. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  54717. currentMesh = scene.meshes[index];
  54718. if (currentMesh._waitingFreezeWorldMatrix) {
  54719. currentMesh.freezeWorldMatrix();
  54720. currentMesh._waitingFreezeWorldMatrix = null;
  54721. }
  54722. else {
  54723. currentMesh.computeWorldMatrix(true);
  54724. }
  54725. }
  54726. }
  54727. // Particles
  54728. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  54729. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  54730. var parsedParticleSystem = parsedData.particleSystems[index];
  54731. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  54732. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  54733. }
  54734. }
  54735. }
  54736. return true;
  54737. }
  54738. catch (err) {
  54739. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  54740. if (onError) {
  54741. onError(msg, err);
  54742. }
  54743. else {
  54744. BABYLON.Tools.Log(msg);
  54745. throw err;
  54746. }
  54747. }
  54748. finally {
  54749. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  54750. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  54751. }
  54752. }
  54753. return false;
  54754. },
  54755. load: function (scene, data, rootUrl, onError) {
  54756. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  54757. // when SceneLoader.debugLogging = true (default), or exception encountered.
  54758. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  54759. // and avoid problems with multiple concurrent .babylon loads.
  54760. var log = "importScene has failed JSON parse";
  54761. try {
  54762. var parsedData = JSON.parse(data);
  54763. log = "";
  54764. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  54765. // Scene
  54766. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  54767. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  54768. }
  54769. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  54770. scene.autoClear = parsedData.autoClear;
  54771. }
  54772. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  54773. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  54774. }
  54775. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  54776. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  54777. }
  54778. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  54779. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  54780. }
  54781. // Fog
  54782. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  54783. scene.fogMode = parsedData.fogMode;
  54784. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  54785. scene.fogStart = parsedData.fogStart;
  54786. scene.fogEnd = parsedData.fogEnd;
  54787. scene.fogDensity = parsedData.fogDensity;
  54788. log += "\tFog mode for scene: ";
  54789. switch (scene.fogMode) {
  54790. // getters not compiling, so using hardcoded
  54791. case 1:
  54792. log += "exp\n";
  54793. break;
  54794. case 2:
  54795. log += "exp2\n";
  54796. break;
  54797. case 3:
  54798. log += "linear\n";
  54799. break;
  54800. }
  54801. }
  54802. //Physics
  54803. if (parsedData.physicsEnabled) {
  54804. var physicsPlugin;
  54805. if (parsedData.physicsEngine === "cannon") {
  54806. physicsPlugin = new BABYLON.CannonJSPlugin();
  54807. }
  54808. else if (parsedData.physicsEngine === "oimo") {
  54809. physicsPlugin = new BABYLON.OimoJSPlugin();
  54810. }
  54811. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  54812. //else - default engine, which is currently oimo
  54813. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  54814. scene.enablePhysics(physicsGravity, physicsPlugin);
  54815. }
  54816. // Metadata
  54817. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  54818. scene.metadata = parsedData.metadata;
  54819. }
  54820. //collisions, if defined. otherwise, default is true
  54821. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  54822. scene.collisionsEnabled = parsedData.collisionsEnabled;
  54823. }
  54824. scene.workerCollisions = !!parsedData.workerCollisions;
  54825. var index;
  54826. var cache;
  54827. // Lights
  54828. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  54829. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  54830. var parsedLight = parsedData.lights[index];
  54831. var light = BABYLON.Light.Parse(parsedLight, scene);
  54832. if (light) {
  54833. log += (index === 0 ? "\n\tLights:" : "");
  54834. log += "\n\t\t" + light.toString(fullDetails);
  54835. }
  54836. }
  54837. }
  54838. // Animations
  54839. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  54840. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  54841. var parsedAnimation = parsedData.animations[index];
  54842. var animation = BABYLON.Animation.Parse(parsedAnimation);
  54843. scene.animations.push(animation);
  54844. log += (index === 0 ? "\n\tAnimations:" : "");
  54845. log += "\n\t\t" + animation.toString(fullDetails);
  54846. }
  54847. }
  54848. if (parsedData.autoAnimate) {
  54849. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  54850. }
  54851. // Materials
  54852. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  54853. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  54854. var parsedMaterial = parsedData.materials[index];
  54855. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  54856. log += (index === 0 ? "\n\tMaterials:" : "");
  54857. log += "\n\t\t" + mat.toString(fullDetails);
  54858. }
  54859. }
  54860. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  54861. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  54862. var parsedMultiMaterial = parsedData.multiMaterials[index];
  54863. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  54864. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  54865. log += "\n\t\t" + mmat.toString(fullDetails);
  54866. }
  54867. }
  54868. // Morph targets
  54869. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  54870. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  54871. var managerData = _a[_i];
  54872. BABYLON.MorphTargetManager.Parse(managerData, scene);
  54873. }
  54874. }
  54875. // Skeletons
  54876. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  54877. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  54878. var parsedSkeleton = parsedData.skeletons[index];
  54879. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  54880. log += (index === 0 ? "\n\tSkeletons:" : "");
  54881. log += "\n\t\t" + skeleton.toString(fullDetails);
  54882. }
  54883. }
  54884. // Geometries
  54885. var geometries = parsedData.geometries;
  54886. if (geometries !== undefined && geometries !== null) {
  54887. // Boxes
  54888. var boxes = geometries.boxes;
  54889. if (boxes !== undefined && boxes !== null) {
  54890. for (index = 0, cache = boxes.length; index < cache; index++) {
  54891. var parsedBox = boxes[index];
  54892. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  54893. }
  54894. }
  54895. // Spheres
  54896. var spheres = geometries.spheres;
  54897. if (spheres !== undefined && spheres !== null) {
  54898. for (index = 0, cache = spheres.length; index < cache; index++) {
  54899. var parsedSphere = spheres[index];
  54900. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  54901. }
  54902. }
  54903. // Cylinders
  54904. var cylinders = geometries.cylinders;
  54905. if (cylinders !== undefined && cylinders !== null) {
  54906. for (index = 0, cache = cylinders.length; index < cache; index++) {
  54907. var parsedCylinder = cylinders[index];
  54908. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  54909. }
  54910. }
  54911. // Toruses
  54912. var toruses = geometries.toruses;
  54913. if (toruses !== undefined && toruses !== null) {
  54914. for (index = 0, cache = toruses.length; index < cache; index++) {
  54915. var parsedTorus = toruses[index];
  54916. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  54917. }
  54918. }
  54919. // Grounds
  54920. var grounds = geometries.grounds;
  54921. if (grounds !== undefined && grounds !== null) {
  54922. for (index = 0, cache = grounds.length; index < cache; index++) {
  54923. var parsedGround = grounds[index];
  54924. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  54925. }
  54926. }
  54927. // Planes
  54928. var planes = geometries.planes;
  54929. if (planes !== undefined && planes !== null) {
  54930. for (index = 0, cache = planes.length; index < cache; index++) {
  54931. var parsedPlane = planes[index];
  54932. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  54933. }
  54934. }
  54935. // TorusKnots
  54936. var torusKnots = geometries.torusKnots;
  54937. if (torusKnots !== undefined && torusKnots !== null) {
  54938. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  54939. var parsedTorusKnot = torusKnots[index];
  54940. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  54941. }
  54942. }
  54943. // VertexData
  54944. var vertexData = geometries.vertexData;
  54945. if (vertexData !== undefined && vertexData !== null) {
  54946. for (index = 0, cache = vertexData.length; index < cache; index++) {
  54947. var parsedVertexData = vertexData[index];
  54948. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  54949. }
  54950. }
  54951. }
  54952. // Transform nodes
  54953. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  54954. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  54955. var parsedTransformNode = parsedData.transformNodes[index];
  54956. BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  54957. }
  54958. }
  54959. // Meshes
  54960. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  54961. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  54962. var parsedMesh = parsedData.meshes[index];
  54963. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  54964. log += (index === 0 ? "\n\tMeshes:" : "");
  54965. log += "\n\t\t" + mesh.toString(fullDetails);
  54966. }
  54967. }
  54968. // Cameras
  54969. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  54970. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  54971. var parsedCamera = parsedData.cameras[index];
  54972. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  54973. log += (index === 0 ? "\n\tCameras:" : "");
  54974. log += "\n\t\t" + camera.toString(fullDetails);
  54975. }
  54976. }
  54977. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  54978. scene.setActiveCameraByID(parsedData.activeCameraID);
  54979. }
  54980. // Browsing all the graph to connect the dots
  54981. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  54982. var camera = scene.cameras[index];
  54983. if (camera._waitingParentId) {
  54984. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  54985. camera._waitingParentId = null;
  54986. }
  54987. }
  54988. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  54989. var light_1 = scene.lights[index];
  54990. if (light_1 && light_1._waitingParentId) {
  54991. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  54992. light_1._waitingParentId = null;
  54993. }
  54994. }
  54995. // Sounds
  54996. var loadedSounds = [];
  54997. var loadedSound;
  54998. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  54999. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  55000. var parsedSound = parsedData.sounds[index];
  55001. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55002. if (!parsedSound.url)
  55003. parsedSound.url = parsedSound.name;
  55004. if (!loadedSounds[parsedSound.url]) {
  55005. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  55006. loadedSounds[parsedSound.url] = loadedSound;
  55007. }
  55008. else {
  55009. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  55010. }
  55011. }
  55012. else {
  55013. new BABYLON.Sound(parsedSound.name, null, scene);
  55014. }
  55015. }
  55016. }
  55017. loadedSounds = [];
  55018. // Connect parents & children and parse actions
  55019. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  55020. var transformNode = scene.transformNodes[index];
  55021. if (transformNode._waitingParentId) {
  55022. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  55023. transformNode._waitingParentId = null;
  55024. }
  55025. }
  55026. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  55027. var mesh = scene.meshes[index];
  55028. if (mesh._waitingParentId) {
  55029. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  55030. mesh._waitingParentId = null;
  55031. }
  55032. if (mesh._waitingActions) {
  55033. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  55034. mesh._waitingActions = null;
  55035. }
  55036. }
  55037. // freeze world matrix application
  55038. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  55039. var currentMesh = scene.meshes[index];
  55040. if (currentMesh._waitingFreezeWorldMatrix) {
  55041. currentMesh.freezeWorldMatrix();
  55042. currentMesh._waitingFreezeWorldMatrix = null;
  55043. }
  55044. else {
  55045. currentMesh.computeWorldMatrix(true);
  55046. }
  55047. }
  55048. // Particles Systems
  55049. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  55050. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  55051. var parsedParticleSystem = parsedData.particleSystems[index];
  55052. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  55053. }
  55054. }
  55055. // Environment texture
  55056. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  55057. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  55058. if (parsedData.createDefaultSkybox === true) {
  55059. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  55060. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  55061. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  55062. }
  55063. }
  55064. // Lens flares
  55065. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  55066. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  55067. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  55068. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  55069. }
  55070. }
  55071. // Shadows
  55072. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  55073. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  55074. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  55075. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  55076. }
  55077. }
  55078. // Lights exclusions / inclusions
  55079. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  55080. var light_2 = scene.lights[index];
  55081. // Excluded check
  55082. if (light_2._excludedMeshesIds.length > 0) {
  55083. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  55084. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  55085. if (excludedMesh) {
  55086. light_2.excludedMeshes.push(excludedMesh);
  55087. }
  55088. }
  55089. light_2._excludedMeshesIds = [];
  55090. }
  55091. // Included check
  55092. if (light_2._includedOnlyMeshesIds.length > 0) {
  55093. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  55094. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  55095. if (includedOnlyMesh) {
  55096. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  55097. }
  55098. }
  55099. light_2._includedOnlyMeshesIds = [];
  55100. }
  55101. }
  55102. // Actions (scene)
  55103. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  55104. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  55105. }
  55106. // Finish
  55107. return true;
  55108. }
  55109. catch (err) {
  55110. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  55111. if (onError) {
  55112. onError(msg, err);
  55113. }
  55114. else {
  55115. BABYLON.Tools.Log(msg);
  55116. throw err;
  55117. }
  55118. }
  55119. finally {
  55120. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  55121. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  55122. }
  55123. }
  55124. return false;
  55125. }
  55126. });
  55127. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  55128. })(BABYLON || (BABYLON = {}));
  55129. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  55130. var BABYLON;
  55131. (function (BABYLON) {
  55132. var FilesInput = /** @class */ (function () {
  55133. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  55134. this.onProcessFileCallback = function () { return true; };
  55135. this._engine = engine;
  55136. this._currentScene = scene;
  55137. this._sceneLoadedCallback = sceneLoadedCallback;
  55138. this._progressCallback = progressCallback;
  55139. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  55140. this._textureLoadingCallback = textureLoadingCallback;
  55141. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  55142. this._onReloadCallback = onReloadCallback;
  55143. this._errorCallback = errorCallback;
  55144. }
  55145. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  55146. var _this = this;
  55147. if (elementToMonitor) {
  55148. this._elementToMonitor = elementToMonitor;
  55149. this._dragEnterHandler = function (e) { _this.drag(e); };
  55150. this._dragOverHandler = function (e) { _this.drag(e); };
  55151. this._dropHandler = function (e) { _this.drop(e); };
  55152. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  55153. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  55154. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  55155. }
  55156. };
  55157. FilesInput.prototype.dispose = function () {
  55158. if (!this._elementToMonitor) {
  55159. return;
  55160. }
  55161. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  55162. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  55163. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  55164. };
  55165. FilesInput.prototype.renderFunction = function () {
  55166. if (this._additionalRenderLoopLogicCallback) {
  55167. this._additionalRenderLoopLogicCallback();
  55168. }
  55169. if (this._currentScene) {
  55170. if (this._textureLoadingCallback) {
  55171. var remaining = this._currentScene.getWaitingItemsCount();
  55172. if (remaining > 0) {
  55173. this._textureLoadingCallback(remaining);
  55174. }
  55175. }
  55176. this._currentScene.render();
  55177. }
  55178. };
  55179. FilesInput.prototype.drag = function (e) {
  55180. e.stopPropagation();
  55181. e.preventDefault();
  55182. };
  55183. FilesInput.prototype.drop = function (eventDrop) {
  55184. eventDrop.stopPropagation();
  55185. eventDrop.preventDefault();
  55186. this.loadFiles(eventDrop);
  55187. };
  55188. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  55189. var _this = this;
  55190. var reader = folder.createReader();
  55191. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  55192. reader.readEntries(function (entries) {
  55193. remaining.count += entries.length;
  55194. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  55195. var entry = entries_1[_i];
  55196. if (entry.isFile) {
  55197. entry.file(function (file) {
  55198. file.correctName = relativePath + file.name;
  55199. files.push(file);
  55200. if (--remaining.count === 0) {
  55201. callback();
  55202. }
  55203. });
  55204. }
  55205. else if (entry.isDirectory) {
  55206. _this._traverseFolder(entry, files, remaining, callback);
  55207. }
  55208. }
  55209. if (--remaining.count) {
  55210. callback();
  55211. }
  55212. });
  55213. };
  55214. FilesInput.prototype._processFiles = function (files) {
  55215. for (var i = 0; i < files.length; i++) {
  55216. var name = files[i].correctName.toLowerCase();
  55217. var extension = name.split('.').pop();
  55218. if (!this.onProcessFileCallback(files[i], name, extension)) {
  55219. continue;
  55220. }
  55221. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  55222. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  55223. this._sceneFileToLoad = files[i];
  55224. }
  55225. else {
  55226. FilesInput.FilesToLoad[name] = files[i];
  55227. }
  55228. }
  55229. };
  55230. FilesInput.prototype.loadFiles = function (event) {
  55231. var _this = this;
  55232. if (this._startingProcessingFilesCallback)
  55233. this._startingProcessingFilesCallback();
  55234. // Handling data transfer via drag'n'drop
  55235. if (event && event.dataTransfer && event.dataTransfer.files) {
  55236. this._filesToLoad = event.dataTransfer.files;
  55237. }
  55238. // Handling files from input files
  55239. if (event && event.target && event.target.files) {
  55240. this._filesToLoad = event.target.files;
  55241. }
  55242. if (this._filesToLoad && this._filesToLoad.length > 0) {
  55243. var files_1 = new Array();
  55244. var folders = [];
  55245. var items = event.dataTransfer ? event.dataTransfer.items : null;
  55246. for (var i = 0; i < this._filesToLoad.length; i++) {
  55247. var fileToLoad = this._filesToLoad[i];
  55248. var name_1 = fileToLoad.name.toLowerCase();
  55249. var entry = void 0;
  55250. fileToLoad.correctName = name_1;
  55251. if (items) {
  55252. var item = items[i];
  55253. if (item.getAsEntry) {
  55254. entry = item.getAsEntry();
  55255. }
  55256. else if (item.webkitGetAsEntry) {
  55257. entry = item.webkitGetAsEntry();
  55258. }
  55259. }
  55260. if (!entry) {
  55261. files_1.push(fileToLoad);
  55262. }
  55263. else {
  55264. if (entry.isDirectory) {
  55265. folders.push(entry);
  55266. }
  55267. else {
  55268. files_1.push(fileToLoad);
  55269. }
  55270. }
  55271. }
  55272. if (folders.length === 0) {
  55273. this._processFiles(files_1);
  55274. this._processReload();
  55275. }
  55276. else {
  55277. var remaining = { count: folders.length };
  55278. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  55279. var folder = folders_1[_i];
  55280. this._traverseFolder(folder, files_1, remaining, function () {
  55281. _this._processFiles(files_1);
  55282. if (remaining.count === 0) {
  55283. _this._processReload();
  55284. }
  55285. });
  55286. }
  55287. }
  55288. }
  55289. };
  55290. FilesInput.prototype._processReload = function () {
  55291. if (this._onReloadCallback) {
  55292. this._onReloadCallback(this._sceneFileToLoad);
  55293. }
  55294. else {
  55295. this.reload();
  55296. }
  55297. };
  55298. FilesInput.prototype.reload = function () {
  55299. var _this = this;
  55300. // If a scene file has been provided
  55301. if (this._sceneFileToLoad) {
  55302. if (this._currentScene) {
  55303. if (BABYLON.Tools.errorsCount > 0) {
  55304. BABYLON.Tools.ClearLogCache();
  55305. }
  55306. this._engine.stopRenderLoop();
  55307. this._currentScene.dispose();
  55308. }
  55309. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  55310. _this._currentScene = newScene;
  55311. if (_this._sceneLoadedCallback) {
  55312. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  55313. }
  55314. // Wait for textures and shaders to be ready
  55315. _this._currentScene.executeWhenReady(function () {
  55316. _this._engine.runRenderLoop(function () {
  55317. _this.renderFunction();
  55318. });
  55319. });
  55320. }, function (progress) {
  55321. if (_this._progressCallback) {
  55322. _this._progressCallback(progress);
  55323. }
  55324. }, function (scene, message) {
  55325. _this._currentScene = scene;
  55326. if (_this._errorCallback) {
  55327. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  55328. }
  55329. });
  55330. }
  55331. else {
  55332. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  55333. }
  55334. };
  55335. FilesInput.FilesToLoad = {};
  55336. return FilesInput;
  55337. }());
  55338. BABYLON.FilesInput = FilesInput;
  55339. })(BABYLON || (BABYLON = {}));
  55340. //# sourceMappingURL=babylon.filesInput.js.map
  55341. var BABYLON;
  55342. (function (BABYLON) {
  55343. /**
  55344. * This class implement a typical dictionary using a string as key and the generic type T as value.
  55345. * The underlying implementation relies on an associative array to ensure the best performances.
  55346. * The value can be anything including 'null' but except 'undefined'
  55347. */
  55348. var StringDictionary = /** @class */ (function () {
  55349. function StringDictionary() {
  55350. this._count = 0;
  55351. this._data = {};
  55352. }
  55353. /**
  55354. * This will clear this dictionary and copy the content from the 'source' one.
  55355. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  55356. * @param source the dictionary to take the content from and copy to this dictionary
  55357. */
  55358. StringDictionary.prototype.copyFrom = function (source) {
  55359. var _this = this;
  55360. this.clear();
  55361. source.forEach(function (t, v) { return _this.add(t, v); });
  55362. };
  55363. /**
  55364. * Get a value based from its key
  55365. * @param key the given key to get the matching value from
  55366. * @return the value if found, otherwise undefined is returned
  55367. */
  55368. StringDictionary.prototype.get = function (key) {
  55369. var val = this._data[key];
  55370. if (val !== undefined) {
  55371. return val;
  55372. }
  55373. return undefined;
  55374. };
  55375. /**
  55376. * Get a value from its key or add it if it doesn't exist.
  55377. * This method will ensure you that a given key/data will be present in the dictionary.
  55378. * @param key the given key to get the matching value from
  55379. * @param factory the factory that will create the value if the key is not present in the dictionary.
  55380. * The factory will only be invoked if there's no data for the given key.
  55381. * @return the value corresponding to the key.
  55382. */
  55383. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  55384. var val = this.get(key);
  55385. if (val !== undefined) {
  55386. return val;
  55387. }
  55388. val = factory(key);
  55389. if (val) {
  55390. this.add(key, val);
  55391. }
  55392. return val;
  55393. };
  55394. /**
  55395. * Get a value from its key if present in the dictionary otherwise add it
  55396. * @param key the key to get the value from
  55397. * @param val if there's no such key/value pair in the dictionary add it with this value
  55398. * @return the value corresponding to the key
  55399. */
  55400. StringDictionary.prototype.getOrAdd = function (key, val) {
  55401. var curVal = this.get(key);
  55402. if (curVal !== undefined) {
  55403. return curVal;
  55404. }
  55405. this.add(key, val);
  55406. return val;
  55407. };
  55408. /**
  55409. * Check if there's a given key in the dictionary
  55410. * @param key the key to check for
  55411. * @return true if the key is present, false otherwise
  55412. */
  55413. StringDictionary.prototype.contains = function (key) {
  55414. return this._data[key] !== undefined;
  55415. };
  55416. /**
  55417. * Add a new key and its corresponding value
  55418. * @param key the key to add
  55419. * @param value the value corresponding to the key
  55420. * @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
  55421. */
  55422. StringDictionary.prototype.add = function (key, value) {
  55423. if (this._data[key] !== undefined) {
  55424. return false;
  55425. }
  55426. this._data[key] = value;
  55427. ++this._count;
  55428. return true;
  55429. };
  55430. StringDictionary.prototype.set = function (key, value) {
  55431. if (this._data[key] === undefined) {
  55432. return false;
  55433. }
  55434. this._data[key] = value;
  55435. return true;
  55436. };
  55437. /**
  55438. * Get the element of the given key and remove it from the dictionary
  55439. * @param key
  55440. */
  55441. StringDictionary.prototype.getAndRemove = function (key) {
  55442. var val = this.get(key);
  55443. if (val !== undefined) {
  55444. delete this._data[key];
  55445. --this._count;
  55446. return val;
  55447. }
  55448. return null;
  55449. };
  55450. /**
  55451. * Remove a key/value from the dictionary.
  55452. * @param key the key to remove
  55453. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  55454. */
  55455. StringDictionary.prototype.remove = function (key) {
  55456. if (this.contains(key)) {
  55457. delete this._data[key];
  55458. --this._count;
  55459. return true;
  55460. }
  55461. return false;
  55462. };
  55463. /**
  55464. * Clear the whole content of the dictionary
  55465. */
  55466. StringDictionary.prototype.clear = function () {
  55467. this._data = {};
  55468. this._count = 0;
  55469. };
  55470. Object.defineProperty(StringDictionary.prototype, "count", {
  55471. get: function () {
  55472. return this._count;
  55473. },
  55474. enumerable: true,
  55475. configurable: true
  55476. });
  55477. /**
  55478. * Execute a callback on each key/val of the dictionary.
  55479. * Note that you can remove any element in this dictionary in the callback implementation
  55480. * @param callback the callback to execute on a given key/value pair
  55481. */
  55482. StringDictionary.prototype.forEach = function (callback) {
  55483. for (var cur in this._data) {
  55484. var val = this._data[cur];
  55485. callback(cur, val);
  55486. }
  55487. };
  55488. /**
  55489. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  55490. * If the callback returns null or undefined the method will iterate to the next key/value pair
  55491. * Note that you can remove any element in this dictionary in the callback implementation
  55492. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  55493. */
  55494. StringDictionary.prototype.first = function (callback) {
  55495. for (var cur in this._data) {
  55496. var val = this._data[cur];
  55497. var res = callback(cur, val);
  55498. if (res) {
  55499. return res;
  55500. }
  55501. }
  55502. return null;
  55503. };
  55504. return StringDictionary;
  55505. }());
  55506. BABYLON.StringDictionary = StringDictionary;
  55507. })(BABYLON || (BABYLON = {}));
  55508. //# sourceMappingURL=babylon.stringDictionary.js.map
  55509. var BABYLON;
  55510. (function (BABYLON) {
  55511. var Tags = /** @class */ (function () {
  55512. function Tags() {
  55513. }
  55514. Tags.EnableFor = function (obj) {
  55515. obj._tags = obj._tags || {};
  55516. obj.hasTags = function () {
  55517. return Tags.HasTags(obj);
  55518. };
  55519. obj.addTags = function (tagsString) {
  55520. return Tags.AddTagsTo(obj, tagsString);
  55521. };
  55522. obj.removeTags = function (tagsString) {
  55523. return Tags.RemoveTagsFrom(obj, tagsString);
  55524. };
  55525. obj.matchesTagsQuery = function (tagsQuery) {
  55526. return Tags.MatchesQuery(obj, tagsQuery);
  55527. };
  55528. };
  55529. Tags.DisableFor = function (obj) {
  55530. delete obj._tags;
  55531. delete obj.hasTags;
  55532. delete obj.addTags;
  55533. delete obj.removeTags;
  55534. delete obj.matchesTagsQuery;
  55535. };
  55536. Tags.HasTags = function (obj) {
  55537. if (!obj._tags) {
  55538. return false;
  55539. }
  55540. return !BABYLON.Tools.IsEmpty(obj._tags);
  55541. };
  55542. Tags.GetTags = function (obj, asString) {
  55543. if (asString === void 0) { asString = true; }
  55544. if (!obj._tags) {
  55545. return null;
  55546. }
  55547. if (asString) {
  55548. var tagsArray = [];
  55549. for (var tag in obj._tags) {
  55550. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  55551. tagsArray.push(tag);
  55552. }
  55553. }
  55554. return tagsArray.join(" ");
  55555. }
  55556. else {
  55557. return obj._tags;
  55558. }
  55559. };
  55560. // the tags 'true' and 'false' are reserved and cannot be used as tags
  55561. // a tag cannot start with '||', '&&', and '!'
  55562. // it cannot contain whitespaces
  55563. Tags.AddTagsTo = function (obj, tagsString) {
  55564. if (!tagsString) {
  55565. return;
  55566. }
  55567. if (typeof tagsString !== "string") {
  55568. return;
  55569. }
  55570. var tags = tagsString.split(" ");
  55571. tags.forEach(function (tag, index, array) {
  55572. Tags._AddTagTo(obj, tag);
  55573. });
  55574. };
  55575. Tags._AddTagTo = function (obj, tag) {
  55576. tag = tag.trim();
  55577. if (tag === "" || tag === "true" || tag === "false") {
  55578. return;
  55579. }
  55580. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  55581. return;
  55582. }
  55583. Tags.EnableFor(obj);
  55584. obj._tags[tag] = true;
  55585. };
  55586. Tags.RemoveTagsFrom = function (obj, tagsString) {
  55587. if (!Tags.HasTags(obj)) {
  55588. return;
  55589. }
  55590. var tags = tagsString.split(" ");
  55591. for (var t in tags) {
  55592. Tags._RemoveTagFrom(obj, tags[t]);
  55593. }
  55594. };
  55595. Tags._RemoveTagFrom = function (obj, tag) {
  55596. delete obj._tags[tag];
  55597. };
  55598. Tags.MatchesQuery = function (obj, tagsQuery) {
  55599. if (tagsQuery === undefined) {
  55600. return true;
  55601. }
  55602. if (tagsQuery === "") {
  55603. return Tags.HasTags(obj);
  55604. }
  55605. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  55606. };
  55607. return Tags;
  55608. }());
  55609. BABYLON.Tags = Tags;
  55610. })(BABYLON || (BABYLON = {}));
  55611. //# sourceMappingURL=babylon.tags.js.map
  55612. var BABYLON;
  55613. (function (BABYLON) {
  55614. var Internals;
  55615. (function (Internals) {
  55616. var AndOrNotEvaluator = /** @class */ (function () {
  55617. function AndOrNotEvaluator() {
  55618. }
  55619. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  55620. if (!query.match(/\([^\(\)]*\)/g)) {
  55621. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  55622. }
  55623. else {
  55624. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  55625. // remove parenthesis
  55626. r = r.slice(1, r.length - 1);
  55627. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  55628. });
  55629. }
  55630. if (query === "true") {
  55631. return true;
  55632. }
  55633. if (query === "false") {
  55634. return false;
  55635. }
  55636. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  55637. };
  55638. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  55639. evaluateCallback = evaluateCallback || (function (r) {
  55640. return r === "true" ? true : false;
  55641. });
  55642. var result;
  55643. var or = parenthesisContent.split("||");
  55644. for (var i in or) {
  55645. if (or.hasOwnProperty(i)) {
  55646. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  55647. var and = ori.split("&&");
  55648. if (and.length > 1) {
  55649. for (var j = 0; j < and.length; ++j) {
  55650. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  55651. if (andj !== "true" && andj !== "false") {
  55652. if (andj[0] === "!") {
  55653. result = !evaluateCallback(andj.substring(1));
  55654. }
  55655. else {
  55656. result = evaluateCallback(andj);
  55657. }
  55658. }
  55659. else {
  55660. result = andj === "true" ? true : false;
  55661. }
  55662. if (!result) {
  55663. ori = "false";
  55664. break;
  55665. }
  55666. }
  55667. }
  55668. if (result || ori === "true") {
  55669. result = true;
  55670. break;
  55671. }
  55672. // result equals false (or undefined)
  55673. if (ori !== "true" && ori !== "false") {
  55674. if (ori[0] === "!") {
  55675. result = !evaluateCallback(ori.substring(1));
  55676. }
  55677. else {
  55678. result = evaluateCallback(ori);
  55679. }
  55680. }
  55681. else {
  55682. result = ori === "true" ? true : false;
  55683. }
  55684. }
  55685. }
  55686. // the whole parenthesis scope is replaced by 'true' or 'false'
  55687. return result ? "true" : "false";
  55688. };
  55689. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  55690. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  55691. // remove whitespaces
  55692. r = r.replace(/[\s]/g, function () { return ""; });
  55693. return r.length % 2 ? "!" : "";
  55694. });
  55695. booleanString = booleanString.trim();
  55696. if (booleanString === "!true") {
  55697. booleanString = "false";
  55698. }
  55699. else if (booleanString === "!false") {
  55700. booleanString = "true";
  55701. }
  55702. return booleanString;
  55703. };
  55704. return AndOrNotEvaluator;
  55705. }());
  55706. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  55707. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  55708. })(BABYLON || (BABYLON = {}));
  55709. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  55710. var BABYLON;
  55711. (function (BABYLON) {
  55712. var Database = /** @class */ (function () {
  55713. function Database(urlToScene, callbackManifestChecked) {
  55714. // Handling various flavors of prefixed version of IndexedDB
  55715. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  55716. this.callbackManifestChecked = callbackManifestChecked;
  55717. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  55718. this.db = null;
  55719. this._enableSceneOffline = false;
  55720. this._enableTexturesOffline = false;
  55721. this.manifestVersionFound = 0;
  55722. this.mustUpdateRessources = false;
  55723. this.hasReachedQuota = false;
  55724. if (!Database.IDBStorageEnabled) {
  55725. this.callbackManifestChecked(true);
  55726. }
  55727. else {
  55728. this.checkManifestFile();
  55729. }
  55730. }
  55731. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  55732. get: function () {
  55733. return this._enableSceneOffline;
  55734. },
  55735. enumerable: true,
  55736. configurable: true
  55737. });
  55738. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  55739. get: function () {
  55740. return this._enableTexturesOffline;
  55741. },
  55742. enumerable: true,
  55743. configurable: true
  55744. });
  55745. Database.prototype.checkManifestFile = function () {
  55746. var _this = this;
  55747. var noManifestFile = function () {
  55748. _this._enableSceneOffline = false;
  55749. _this._enableTexturesOffline = false;
  55750. _this.callbackManifestChecked(false);
  55751. };
  55752. var timeStampUsed = false;
  55753. var manifestURL = this.currentSceneUrl + ".manifest";
  55754. var xhr = new XMLHttpRequest();
  55755. if (navigator.onLine) {
  55756. // Adding a timestamp to by-pass browsers' cache
  55757. timeStampUsed = true;
  55758. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  55759. }
  55760. xhr.open("GET", manifestURL, true);
  55761. xhr.addEventListener("load", function () {
  55762. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  55763. try {
  55764. var manifestFile = JSON.parse(xhr.response);
  55765. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  55766. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  55767. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  55768. _this.manifestVersionFound = manifestFile.version;
  55769. }
  55770. if (_this.callbackManifestChecked) {
  55771. _this.callbackManifestChecked(true);
  55772. }
  55773. }
  55774. catch (ex) {
  55775. noManifestFile();
  55776. }
  55777. }
  55778. else {
  55779. noManifestFile();
  55780. }
  55781. }, false);
  55782. xhr.addEventListener("error", function (event) {
  55783. if (timeStampUsed) {
  55784. timeStampUsed = false;
  55785. // Let's retry without the timeStamp
  55786. // It could fail when coupled with HTML5 Offline API
  55787. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  55788. xhr.open("GET", retryManifestURL, true);
  55789. xhr.send();
  55790. }
  55791. else {
  55792. noManifestFile();
  55793. }
  55794. }, false);
  55795. try {
  55796. xhr.send();
  55797. }
  55798. catch (ex) {
  55799. BABYLON.Tools.Error("Error on XHR send request.");
  55800. this.callbackManifestChecked(false);
  55801. }
  55802. };
  55803. Database.prototype.openAsync = function (successCallback, errorCallback) {
  55804. var _this = this;
  55805. var handleError = function () {
  55806. _this.isSupported = false;
  55807. if (errorCallback)
  55808. errorCallback();
  55809. };
  55810. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  55811. // Your browser doesn't support IndexedDB
  55812. this.isSupported = false;
  55813. if (errorCallback)
  55814. errorCallback();
  55815. }
  55816. else {
  55817. // If the DB hasn't been opened or created yet
  55818. if (!this.db) {
  55819. this.hasReachedQuota = false;
  55820. this.isSupported = true;
  55821. var request = this.idbFactory.open("babylonjs", 1);
  55822. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  55823. request.onerror = function (event) {
  55824. handleError();
  55825. };
  55826. // executes when a version change transaction cannot complete due to other active transactions
  55827. request.onblocked = function (event) {
  55828. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  55829. handleError();
  55830. };
  55831. // DB has been opened successfully
  55832. request.onsuccess = function (event) {
  55833. _this.db = request.result;
  55834. successCallback();
  55835. };
  55836. // Initialization of the DB. Creating Scenes & Textures stores
  55837. request.onupgradeneeded = function (event) {
  55838. _this.db = (event.target).result;
  55839. if (_this.db) {
  55840. try {
  55841. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  55842. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  55843. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  55844. }
  55845. catch (ex) {
  55846. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  55847. handleError();
  55848. }
  55849. }
  55850. };
  55851. }
  55852. else {
  55853. if (successCallback)
  55854. successCallback();
  55855. }
  55856. }
  55857. };
  55858. Database.prototype.loadImageFromDB = function (url, image) {
  55859. var _this = this;
  55860. var completeURL = Database.ReturnFullUrlLocation(url);
  55861. var saveAndLoadImage = function () {
  55862. if (!_this.hasReachedQuota && _this.db !== null) {
  55863. // the texture is not yet in the DB, let's try to save it
  55864. _this._saveImageIntoDBAsync(completeURL, image);
  55865. }
  55866. else {
  55867. image.src = url;
  55868. }
  55869. };
  55870. if (!this.mustUpdateRessources) {
  55871. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  55872. }
  55873. else {
  55874. saveAndLoadImage();
  55875. }
  55876. };
  55877. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  55878. if (this.isSupported && this.db !== null) {
  55879. var texture;
  55880. var transaction = this.db.transaction(["textures"]);
  55881. transaction.onabort = function (event) {
  55882. image.src = url;
  55883. };
  55884. transaction.oncomplete = function (event) {
  55885. var blobTextureURL;
  55886. if (texture) {
  55887. var URL = window.URL || window.webkitURL;
  55888. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  55889. image.onerror = function () {
  55890. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  55891. image.src = url;
  55892. };
  55893. image.src = blobTextureURL;
  55894. }
  55895. else {
  55896. notInDBCallback();
  55897. }
  55898. };
  55899. var getRequest = transaction.objectStore("textures").get(url);
  55900. getRequest.onsuccess = function (event) {
  55901. texture = (event.target).result;
  55902. };
  55903. getRequest.onerror = function (event) {
  55904. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  55905. image.src = url;
  55906. };
  55907. }
  55908. else {
  55909. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  55910. image.src = url;
  55911. }
  55912. };
  55913. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  55914. var _this = this;
  55915. if (this.isSupported) {
  55916. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  55917. var generateBlobUrl = function () {
  55918. var blobTextureURL;
  55919. if (blob) {
  55920. var URL = window.URL || window.webkitURL;
  55921. try {
  55922. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  55923. }
  55924. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  55925. catch (ex) {
  55926. blobTextureURL = URL.createObjectURL(blob);
  55927. }
  55928. }
  55929. if (blobTextureURL) {
  55930. image.src = blobTextureURL;
  55931. }
  55932. };
  55933. if (Database.IsUASupportingBlobStorage) {
  55934. var xhr = new XMLHttpRequest(), blob;
  55935. xhr.open("GET", url, true);
  55936. xhr.responseType = "blob";
  55937. xhr.addEventListener("load", function () {
  55938. if (xhr.status === 200 && _this.db) {
  55939. // Blob as response (XHR2)
  55940. blob = xhr.response;
  55941. var transaction = _this.db.transaction(["textures"], "readwrite");
  55942. // the transaction could abort because of a QuotaExceededError error
  55943. transaction.onabort = function (event) {
  55944. try {
  55945. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  55946. var srcElement = (event.srcElement || event.target);
  55947. var error = srcElement.error;
  55948. if (error && error.name === "QuotaExceededError") {
  55949. _this.hasReachedQuota = true;
  55950. }
  55951. }
  55952. catch (ex) { }
  55953. generateBlobUrl();
  55954. };
  55955. transaction.oncomplete = function (event) {
  55956. generateBlobUrl();
  55957. };
  55958. var newTexture = { textureUrl: url, data: blob };
  55959. try {
  55960. // Put the blob into the dabase
  55961. var addRequest = transaction.objectStore("textures").put(newTexture);
  55962. addRequest.onsuccess = function (event) {
  55963. };
  55964. addRequest.onerror = function (event) {
  55965. generateBlobUrl();
  55966. };
  55967. }
  55968. catch (ex) {
  55969. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  55970. if (ex.code === 25) {
  55971. Database.IsUASupportingBlobStorage = false;
  55972. }
  55973. image.src = url;
  55974. }
  55975. }
  55976. else {
  55977. image.src = url;
  55978. }
  55979. }, false);
  55980. xhr.addEventListener("error", function (event) {
  55981. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  55982. image.src = url;
  55983. }, false);
  55984. xhr.send();
  55985. }
  55986. else {
  55987. image.src = url;
  55988. }
  55989. }
  55990. else {
  55991. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  55992. image.src = url;
  55993. }
  55994. };
  55995. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  55996. var _this = this;
  55997. var updateVersion = function () {
  55998. // the version is not yet in the DB or we need to update it
  55999. _this._saveVersionIntoDBAsync(url, versionLoaded);
  56000. };
  56001. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  56002. };
  56003. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  56004. var _this = this;
  56005. if (this.isSupported && this.db) {
  56006. var version;
  56007. try {
  56008. var transaction = this.db.transaction(["versions"]);
  56009. transaction.oncomplete = function (event) {
  56010. if (version) {
  56011. // If the version in the JSON file is > than the version in DB
  56012. if (_this.manifestVersionFound > version.data) {
  56013. _this.mustUpdateRessources = true;
  56014. updateInDBCallback();
  56015. }
  56016. else {
  56017. callback(version.data);
  56018. }
  56019. }
  56020. else {
  56021. _this.mustUpdateRessources = true;
  56022. updateInDBCallback();
  56023. }
  56024. };
  56025. transaction.onabort = function (event) {
  56026. callback(-1);
  56027. };
  56028. var getRequest = transaction.objectStore("versions").get(url);
  56029. getRequest.onsuccess = function (event) {
  56030. version = (event.target).result;
  56031. };
  56032. getRequest.onerror = function (event) {
  56033. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  56034. callback(-1);
  56035. };
  56036. }
  56037. catch (ex) {
  56038. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  56039. callback(-1);
  56040. }
  56041. }
  56042. else {
  56043. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  56044. callback(-1);
  56045. }
  56046. };
  56047. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  56048. var _this = this;
  56049. if (this.isSupported && !this.hasReachedQuota && this.db) {
  56050. try {
  56051. // Open a transaction to the database
  56052. var transaction = this.db.transaction(["versions"], "readwrite");
  56053. // the transaction could abort because of a QuotaExceededError error
  56054. transaction.onabort = function (event) {
  56055. try {
  56056. var error = event.srcElement['error'];
  56057. if (error && error.name === "QuotaExceededError") {
  56058. _this.hasReachedQuota = true;
  56059. }
  56060. }
  56061. catch (ex) { }
  56062. callback(-1);
  56063. };
  56064. transaction.oncomplete = function (event) {
  56065. callback(_this.manifestVersionFound);
  56066. };
  56067. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  56068. // Put the scene into the database
  56069. var addRequest = transaction.objectStore("versions").put(newVersion);
  56070. addRequest.onsuccess = function (event) {
  56071. };
  56072. addRequest.onerror = function (event) {
  56073. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  56074. };
  56075. }
  56076. catch (ex) {
  56077. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  56078. callback(-1);
  56079. }
  56080. }
  56081. else {
  56082. callback(-1);
  56083. }
  56084. };
  56085. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  56086. var _this = this;
  56087. var completeUrl = Database.ReturnFullUrlLocation(url);
  56088. var saveAndLoadFile = function () {
  56089. // the scene is not yet in the DB, let's try to save it
  56090. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  56091. };
  56092. this._checkVersionFromDB(completeUrl, function (version) {
  56093. if (version !== -1) {
  56094. if (!_this.mustUpdateRessources) {
  56095. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  56096. }
  56097. else {
  56098. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  56099. }
  56100. }
  56101. else {
  56102. if (errorCallback) {
  56103. errorCallback();
  56104. }
  56105. }
  56106. });
  56107. };
  56108. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  56109. if (this.isSupported && this.db) {
  56110. var targetStore;
  56111. if (url.indexOf(".babylon") !== -1) {
  56112. targetStore = "scenes";
  56113. }
  56114. else {
  56115. targetStore = "textures";
  56116. }
  56117. var file;
  56118. var transaction = this.db.transaction([targetStore]);
  56119. transaction.oncomplete = function (event) {
  56120. if (file) {
  56121. callback(file.data);
  56122. }
  56123. else {
  56124. notInDBCallback();
  56125. }
  56126. };
  56127. transaction.onabort = function (event) {
  56128. notInDBCallback();
  56129. };
  56130. var getRequest = transaction.objectStore(targetStore).get(url);
  56131. getRequest.onsuccess = function (event) {
  56132. file = (event.target).result;
  56133. };
  56134. getRequest.onerror = function (event) {
  56135. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  56136. notInDBCallback();
  56137. };
  56138. }
  56139. else {
  56140. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  56141. callback();
  56142. }
  56143. };
  56144. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  56145. var _this = this;
  56146. if (this.isSupported) {
  56147. var targetStore;
  56148. if (url.indexOf(".babylon") !== -1) {
  56149. targetStore = "scenes";
  56150. }
  56151. else {
  56152. targetStore = "textures";
  56153. }
  56154. // Create XHR
  56155. var xhr = new XMLHttpRequest();
  56156. var fileData;
  56157. xhr.open("GET", url, true);
  56158. if (useArrayBuffer) {
  56159. xhr.responseType = "arraybuffer";
  56160. }
  56161. if (progressCallback) {
  56162. xhr.onprogress = progressCallback;
  56163. }
  56164. xhr.addEventListener("load", function () {
  56165. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  56166. // Blob as response (XHR2)
  56167. //fileData = xhr.responseText;
  56168. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  56169. if (!_this.hasReachedQuota && _this.db) {
  56170. // Open a transaction to the database
  56171. var transaction = _this.db.transaction([targetStore], "readwrite");
  56172. // the transaction could abort because of a QuotaExceededError error
  56173. transaction.onabort = function (event) {
  56174. try {
  56175. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  56176. var error = event.srcElement['error'];
  56177. if (error && error.name === "QuotaExceededError") {
  56178. _this.hasReachedQuota = true;
  56179. }
  56180. }
  56181. catch (ex) { }
  56182. callback(fileData);
  56183. };
  56184. transaction.oncomplete = function (event) {
  56185. callback(fileData);
  56186. };
  56187. var newFile;
  56188. if (targetStore === "scenes") {
  56189. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  56190. }
  56191. else {
  56192. newFile = { textureUrl: url, data: fileData };
  56193. }
  56194. try {
  56195. // Put the scene into the database
  56196. var addRequest = transaction.objectStore(targetStore).put(newFile);
  56197. addRequest.onsuccess = function (event) {
  56198. };
  56199. addRequest.onerror = function (event) {
  56200. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  56201. };
  56202. }
  56203. catch (ex) {
  56204. callback(fileData);
  56205. }
  56206. }
  56207. else {
  56208. callback(fileData);
  56209. }
  56210. }
  56211. else {
  56212. callback();
  56213. }
  56214. }, false);
  56215. xhr.addEventListener("error", function (event) {
  56216. BABYLON.Tools.Error("error on XHR request.");
  56217. callback();
  56218. }, false);
  56219. xhr.send();
  56220. }
  56221. else {
  56222. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  56223. callback();
  56224. }
  56225. };
  56226. Database.IsUASupportingBlobStorage = true;
  56227. Database.IDBStorageEnabled = true;
  56228. Database.parseURL = function (url) {
  56229. var a = document.createElement('a');
  56230. a.href = url;
  56231. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  56232. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  56233. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  56234. return absLocation;
  56235. };
  56236. Database.ReturnFullUrlLocation = function (url) {
  56237. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  56238. return (Database.parseURL(window.location.href) + url);
  56239. }
  56240. else {
  56241. return url;
  56242. }
  56243. };
  56244. return Database;
  56245. }());
  56246. BABYLON.Database = Database;
  56247. })(BABYLON || (BABYLON = {}));
  56248. //# sourceMappingURL=babylon.database.js.map
  56249. var BABYLON;
  56250. (function (BABYLON) {
  56251. var FresnelParameters = /** @class */ (function () {
  56252. function FresnelParameters() {
  56253. this._isEnabled = true;
  56254. this.leftColor = BABYLON.Color3.White();
  56255. this.rightColor = BABYLON.Color3.Black();
  56256. this.bias = 0;
  56257. this.power = 1;
  56258. }
  56259. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  56260. get: function () {
  56261. return this._isEnabled;
  56262. },
  56263. set: function (value) {
  56264. if (this._isEnabled === value) {
  56265. return;
  56266. }
  56267. this._isEnabled = value;
  56268. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  56269. },
  56270. enumerable: true,
  56271. configurable: true
  56272. });
  56273. FresnelParameters.prototype.clone = function () {
  56274. var newFresnelParameters = new FresnelParameters();
  56275. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  56276. return newFresnelParameters;
  56277. };
  56278. FresnelParameters.prototype.serialize = function () {
  56279. var serializationObject = {};
  56280. serializationObject.isEnabled = this.isEnabled;
  56281. serializationObject.leftColor = this.leftColor;
  56282. serializationObject.rightColor = this.rightColor;
  56283. serializationObject.bias = this.bias;
  56284. serializationObject.power = this.power;
  56285. return serializationObject;
  56286. };
  56287. FresnelParameters.Parse = function (parsedFresnelParameters) {
  56288. var fresnelParameters = new FresnelParameters();
  56289. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  56290. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  56291. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  56292. fresnelParameters.bias = parsedFresnelParameters.bias;
  56293. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  56294. return fresnelParameters;
  56295. };
  56296. return FresnelParameters;
  56297. }());
  56298. BABYLON.FresnelParameters = FresnelParameters;
  56299. })(BABYLON || (BABYLON = {}));
  56300. //# sourceMappingURL=babylon.fresnelParameters.js.map
  56301. var BABYLON;
  56302. (function (BABYLON) {
  56303. var MultiMaterial = /** @class */ (function (_super) {
  56304. __extends(MultiMaterial, _super);
  56305. function MultiMaterial(name, scene) {
  56306. var _this = _super.call(this, name, scene, true) || this;
  56307. scene.multiMaterials.push(_this);
  56308. _this.subMaterials = new Array();
  56309. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  56310. return _this;
  56311. }
  56312. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  56313. get: function () {
  56314. return this._subMaterials;
  56315. },
  56316. set: function (value) {
  56317. this._subMaterials = value;
  56318. this._hookArray(value);
  56319. },
  56320. enumerable: true,
  56321. configurable: true
  56322. });
  56323. MultiMaterial.prototype._hookArray = function (array) {
  56324. var _this = this;
  56325. var oldPush = array.push;
  56326. array.push = function () {
  56327. var items = [];
  56328. for (var _i = 0; _i < arguments.length; _i++) {
  56329. items[_i] = arguments[_i];
  56330. }
  56331. var result = oldPush.apply(array, items);
  56332. _this._markAllSubMeshesAsTexturesDirty();
  56333. return result;
  56334. };
  56335. var oldSplice = array.splice;
  56336. array.splice = function (index, deleteCount) {
  56337. var deleted = oldSplice.apply(array, [index, deleteCount]);
  56338. _this._markAllSubMeshesAsTexturesDirty();
  56339. return deleted;
  56340. };
  56341. };
  56342. // Properties
  56343. MultiMaterial.prototype.getSubMaterial = function (index) {
  56344. if (index < 0 || index >= this.subMaterials.length) {
  56345. return this.getScene().defaultMaterial;
  56346. }
  56347. return this.subMaterials[index];
  56348. };
  56349. MultiMaterial.prototype.getActiveTextures = function () {
  56350. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  56351. if (subMaterial) {
  56352. return subMaterial.getActiveTextures();
  56353. }
  56354. else {
  56355. return [];
  56356. }
  56357. }));
  56358. var _a;
  56359. };
  56360. // Methods
  56361. MultiMaterial.prototype.getClassName = function () {
  56362. return "MultiMaterial";
  56363. };
  56364. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  56365. for (var index = 0; index < this.subMaterials.length; index++) {
  56366. var subMaterial = this.subMaterials[index];
  56367. if (subMaterial) {
  56368. if (subMaterial.storeEffectOnSubMeshes) {
  56369. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  56370. return false;
  56371. }
  56372. continue;
  56373. }
  56374. if (!subMaterial.isReady(mesh)) {
  56375. return false;
  56376. }
  56377. }
  56378. }
  56379. return true;
  56380. };
  56381. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  56382. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  56383. for (var index = 0; index < this.subMaterials.length; index++) {
  56384. var subMaterial = null;
  56385. var current = this.subMaterials[index];
  56386. if (cloneChildren && current) {
  56387. subMaterial = current.clone(name + "-" + current.name);
  56388. }
  56389. else {
  56390. subMaterial = this.subMaterials[index];
  56391. }
  56392. newMultiMaterial.subMaterials.push(subMaterial);
  56393. }
  56394. return newMultiMaterial;
  56395. };
  56396. MultiMaterial.prototype.serialize = function () {
  56397. var serializationObject = {};
  56398. serializationObject.name = this.name;
  56399. serializationObject.id = this.id;
  56400. if (BABYLON.Tags) {
  56401. serializationObject.tags = BABYLON.Tags.GetTags(this);
  56402. }
  56403. serializationObject.materials = [];
  56404. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  56405. var subMat = this.subMaterials[matIndex];
  56406. if (subMat) {
  56407. serializationObject.materials.push(subMat.id);
  56408. }
  56409. else {
  56410. serializationObject.materials.push(null);
  56411. }
  56412. }
  56413. return serializationObject;
  56414. };
  56415. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  56416. var scene = this.getScene();
  56417. if (!scene) {
  56418. return;
  56419. }
  56420. var index = scene.multiMaterials.indexOf(this);
  56421. if (index >= 0) {
  56422. scene.multiMaterials.splice(index, 1);
  56423. }
  56424. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  56425. };
  56426. return MultiMaterial;
  56427. }(BABYLON.Material));
  56428. BABYLON.MultiMaterial = MultiMaterial;
  56429. })(BABYLON || (BABYLON = {}));
  56430. //# sourceMappingURL=babylon.multiMaterial.js.map
  56431. var BABYLON;
  56432. (function (BABYLON) {
  56433. var FreeCameraTouchInput = /** @class */ (function () {
  56434. function FreeCameraTouchInput() {
  56435. this._offsetX = null;
  56436. this._offsetY = null;
  56437. this._pointerPressed = new Array();
  56438. this.touchAngularSensibility = 200000.0;
  56439. this.touchMoveSensibility = 250.0;
  56440. }
  56441. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  56442. var _this = this;
  56443. var previousPosition = null;
  56444. if (this._pointerInput === undefined) {
  56445. this._onLostFocus = function (evt) {
  56446. _this._offsetX = null;
  56447. _this._offsetY = null;
  56448. };
  56449. this._pointerInput = function (p, s) {
  56450. var evt = p.event;
  56451. if (evt.pointerType === "mouse") {
  56452. return;
  56453. }
  56454. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  56455. if (!noPreventDefault) {
  56456. evt.preventDefault();
  56457. }
  56458. _this._pointerPressed.push(evt.pointerId);
  56459. if (_this._pointerPressed.length !== 1) {
  56460. return;
  56461. }
  56462. previousPosition = {
  56463. x: evt.clientX,
  56464. y: evt.clientY
  56465. };
  56466. }
  56467. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  56468. if (!noPreventDefault) {
  56469. evt.preventDefault();
  56470. }
  56471. var index = _this._pointerPressed.indexOf(evt.pointerId);
  56472. if (index === -1) {
  56473. return;
  56474. }
  56475. _this._pointerPressed.splice(index, 1);
  56476. if (index != 0) {
  56477. return;
  56478. }
  56479. previousPosition = null;
  56480. _this._offsetX = null;
  56481. _this._offsetY = null;
  56482. }
  56483. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  56484. if (!noPreventDefault) {
  56485. evt.preventDefault();
  56486. }
  56487. if (!previousPosition) {
  56488. return;
  56489. }
  56490. var index = _this._pointerPressed.indexOf(evt.pointerId);
  56491. if (index != 0) {
  56492. return;
  56493. }
  56494. _this._offsetX = evt.clientX - previousPosition.x;
  56495. _this._offsetY = -(evt.clientY - previousPosition.y);
  56496. }
  56497. };
  56498. }
  56499. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  56500. if (this._onLostFocus) {
  56501. element.addEventListener("blur", this._onLostFocus);
  56502. }
  56503. };
  56504. FreeCameraTouchInput.prototype.detachControl = function (element) {
  56505. if (this._pointerInput && element) {
  56506. if (this._observer) {
  56507. this.camera.getScene().onPointerObservable.remove(this._observer);
  56508. this._observer = null;
  56509. }
  56510. if (this._onLostFocus) {
  56511. element.removeEventListener("blur", this._onLostFocus);
  56512. this._onLostFocus = null;
  56513. }
  56514. this._pointerPressed = [];
  56515. this._offsetX = null;
  56516. this._offsetY = null;
  56517. }
  56518. };
  56519. FreeCameraTouchInput.prototype.checkInputs = function () {
  56520. if (this._offsetX && this._offsetY) {
  56521. var camera = this.camera;
  56522. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  56523. if (this._pointerPressed.length > 1) {
  56524. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  56525. }
  56526. else {
  56527. var speed = camera._computeLocalCameraSpeed();
  56528. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  56529. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  56530. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  56531. }
  56532. }
  56533. };
  56534. FreeCameraTouchInput.prototype.getClassName = function () {
  56535. return "FreeCameraTouchInput";
  56536. };
  56537. FreeCameraTouchInput.prototype.getSimpleName = function () {
  56538. return "touch";
  56539. };
  56540. __decorate([
  56541. BABYLON.serialize()
  56542. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  56543. __decorate([
  56544. BABYLON.serialize()
  56545. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  56546. return FreeCameraTouchInput;
  56547. }());
  56548. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  56549. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  56550. })(BABYLON || (BABYLON = {}));
  56551. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  56552. var BABYLON;
  56553. (function (BABYLON) {
  56554. // We're mainly based on the logic defined into the FreeCamera code
  56555. var TouchCamera = /** @class */ (function (_super) {
  56556. __extends(TouchCamera, _super);
  56557. //-- end properties for backward compatibility for inputs
  56558. function TouchCamera(name, position, scene) {
  56559. var _this = _super.call(this, name, position, scene) || this;
  56560. _this.inputs.addTouch();
  56561. _this._setupInputs();
  56562. return _this;
  56563. }
  56564. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  56565. //-- Begin properties for backward compatibility for inputs
  56566. get: function () {
  56567. var touch = this.inputs.attached["touch"];
  56568. if (touch)
  56569. return touch.touchAngularSensibility;
  56570. return 0;
  56571. },
  56572. set: function (value) {
  56573. var touch = this.inputs.attached["touch"];
  56574. if (touch)
  56575. touch.touchAngularSensibility = value;
  56576. },
  56577. enumerable: true,
  56578. configurable: true
  56579. });
  56580. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  56581. get: function () {
  56582. var touch = this.inputs.attached["touch"];
  56583. if (touch)
  56584. return touch.touchMoveSensibility;
  56585. return 0;
  56586. },
  56587. set: function (value) {
  56588. var touch = this.inputs.attached["touch"];
  56589. if (touch)
  56590. touch.touchMoveSensibility = value;
  56591. },
  56592. enumerable: true,
  56593. configurable: true
  56594. });
  56595. TouchCamera.prototype.getClassName = function () {
  56596. return "TouchCamera";
  56597. };
  56598. TouchCamera.prototype._setupInputs = function () {
  56599. var mouse = this.inputs.attached["mouse"];
  56600. if (mouse) {
  56601. mouse.touchEnabled = false;
  56602. }
  56603. };
  56604. return TouchCamera;
  56605. }(BABYLON.FreeCamera));
  56606. BABYLON.TouchCamera = TouchCamera;
  56607. })(BABYLON || (BABYLON = {}));
  56608. //# sourceMappingURL=babylon.touchCamera.js.map
  56609. var BABYLON;
  56610. (function (BABYLON) {
  56611. var ProceduralTexture = /** @class */ (function (_super) {
  56612. __extends(ProceduralTexture, _super);
  56613. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  56614. if (fallbackTexture === void 0) { fallbackTexture = null; }
  56615. if (generateMipMaps === void 0) { generateMipMaps = true; }
  56616. if (isCube === void 0) { isCube = false; }
  56617. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  56618. _this.isCube = isCube;
  56619. _this.isEnabled = true;
  56620. _this._currentRefreshId = -1;
  56621. _this._refreshRate = 1;
  56622. _this._vertexBuffers = {};
  56623. _this._uniforms = new Array();
  56624. _this._samplers = new Array();
  56625. _this._textures = {};
  56626. _this._floats = {};
  56627. _this._floatsArrays = {};
  56628. _this._colors3 = {};
  56629. _this._colors4 = {};
  56630. _this._vectors2 = {};
  56631. _this._vectors3 = {};
  56632. _this._matrices = {};
  56633. _this._fallbackTextureUsed = false;
  56634. scene._proceduralTextures.push(_this);
  56635. _this._engine = scene.getEngine();
  56636. _this.name = name;
  56637. _this.isRenderTarget = true;
  56638. _this._size = size;
  56639. _this._generateMipMaps = generateMipMaps;
  56640. _this.setFragment(fragment);
  56641. _this._fallbackTexture = fallbackTexture;
  56642. if (isCube) {
  56643. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  56644. _this.setFloat("face", 0);
  56645. }
  56646. else {
  56647. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  56648. }
  56649. // VBO
  56650. var vertices = [];
  56651. vertices.push(1, 1);
  56652. vertices.push(-1, 1);
  56653. vertices.push(-1, -1);
  56654. vertices.push(1, -1);
  56655. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  56656. _this._createIndexBuffer();
  56657. return _this;
  56658. }
  56659. ProceduralTexture.prototype._createIndexBuffer = function () {
  56660. var engine = this._engine;
  56661. // Indices
  56662. var indices = [];
  56663. indices.push(0);
  56664. indices.push(1);
  56665. indices.push(2);
  56666. indices.push(0);
  56667. indices.push(2);
  56668. indices.push(3);
  56669. this._indexBuffer = engine.createIndexBuffer(indices);
  56670. };
  56671. ProceduralTexture.prototype._rebuild = function () {
  56672. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  56673. if (vb) {
  56674. vb._rebuild();
  56675. }
  56676. this._createIndexBuffer();
  56677. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  56678. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  56679. }
  56680. };
  56681. ProceduralTexture.prototype.reset = function () {
  56682. if (this._effect === undefined) {
  56683. return;
  56684. }
  56685. var engine = this._engine;
  56686. engine._releaseEffect(this._effect);
  56687. };
  56688. ProceduralTexture.prototype.isReady = function () {
  56689. var _this = this;
  56690. var engine = this._engine;
  56691. var shaders;
  56692. if (!this._fragment) {
  56693. return false;
  56694. }
  56695. if (this._fallbackTextureUsed) {
  56696. return true;
  56697. }
  56698. if (this._fragment.fragmentElement !== undefined) {
  56699. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  56700. }
  56701. else {
  56702. shaders = { vertex: "procedural", fragment: this._fragment };
  56703. }
  56704. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  56705. _this.releaseInternalTexture();
  56706. if (_this._fallbackTexture) {
  56707. _this._texture = _this._fallbackTexture._texture;
  56708. if (_this._texture) {
  56709. _this._texture.incrementReferences();
  56710. }
  56711. }
  56712. _this._fallbackTextureUsed = true;
  56713. });
  56714. return this._effect.isReady();
  56715. };
  56716. ProceduralTexture.prototype.resetRefreshCounter = function () {
  56717. this._currentRefreshId = -1;
  56718. };
  56719. ProceduralTexture.prototype.setFragment = function (fragment) {
  56720. this._fragment = fragment;
  56721. };
  56722. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  56723. get: function () {
  56724. return this._refreshRate;
  56725. },
  56726. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  56727. set: function (value) {
  56728. this._refreshRate = value;
  56729. this.resetRefreshCounter();
  56730. },
  56731. enumerable: true,
  56732. configurable: true
  56733. });
  56734. ProceduralTexture.prototype._shouldRender = function () {
  56735. if (!this.isEnabled || !this.isReady() || !this._texture) {
  56736. return false;
  56737. }
  56738. if (this._fallbackTextureUsed) {
  56739. return false;
  56740. }
  56741. if (this._currentRefreshId === -1) {
  56742. this._currentRefreshId = 1;
  56743. return true;
  56744. }
  56745. if (this.refreshRate === this._currentRefreshId) {
  56746. this._currentRefreshId = 1;
  56747. return true;
  56748. }
  56749. this._currentRefreshId++;
  56750. return false;
  56751. };
  56752. ProceduralTexture.prototype.getRenderSize = function () {
  56753. return this._size;
  56754. };
  56755. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  56756. if (this._fallbackTextureUsed) {
  56757. return;
  56758. }
  56759. this.releaseInternalTexture();
  56760. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  56761. };
  56762. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  56763. if (this._uniforms.indexOf(uniformName) === -1) {
  56764. this._uniforms.push(uniformName);
  56765. }
  56766. };
  56767. ProceduralTexture.prototype.setTexture = function (name, texture) {
  56768. if (this._samplers.indexOf(name) === -1) {
  56769. this._samplers.push(name);
  56770. }
  56771. this._textures[name] = texture;
  56772. return this;
  56773. };
  56774. ProceduralTexture.prototype.setFloat = function (name, value) {
  56775. this._checkUniform(name);
  56776. this._floats[name] = value;
  56777. return this;
  56778. };
  56779. ProceduralTexture.prototype.setFloats = function (name, value) {
  56780. this._checkUniform(name);
  56781. this._floatsArrays[name] = value;
  56782. return this;
  56783. };
  56784. ProceduralTexture.prototype.setColor3 = function (name, value) {
  56785. this._checkUniform(name);
  56786. this._colors3[name] = value;
  56787. return this;
  56788. };
  56789. ProceduralTexture.prototype.setColor4 = function (name, value) {
  56790. this._checkUniform(name);
  56791. this._colors4[name] = value;
  56792. return this;
  56793. };
  56794. ProceduralTexture.prototype.setVector2 = function (name, value) {
  56795. this._checkUniform(name);
  56796. this._vectors2[name] = value;
  56797. return this;
  56798. };
  56799. ProceduralTexture.prototype.setVector3 = function (name, value) {
  56800. this._checkUniform(name);
  56801. this._vectors3[name] = value;
  56802. return this;
  56803. };
  56804. ProceduralTexture.prototype.setMatrix = function (name, value) {
  56805. this._checkUniform(name);
  56806. this._matrices[name] = value;
  56807. return this;
  56808. };
  56809. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  56810. var scene = this.getScene();
  56811. if (!scene) {
  56812. return;
  56813. }
  56814. var engine = this._engine;
  56815. // Render
  56816. engine.enableEffect(this._effect);
  56817. engine.setState(false);
  56818. // Texture
  56819. for (var name in this._textures) {
  56820. this._effect.setTexture(name, this._textures[name]);
  56821. }
  56822. // Float
  56823. for (name in this._floats) {
  56824. this._effect.setFloat(name, this._floats[name]);
  56825. }
  56826. // Floats
  56827. for (name in this._floatsArrays) {
  56828. this._effect.setArray(name, this._floatsArrays[name]);
  56829. }
  56830. // Color3
  56831. for (name in this._colors3) {
  56832. this._effect.setColor3(name, this._colors3[name]);
  56833. }
  56834. // Color4
  56835. for (name in this._colors4) {
  56836. var color = this._colors4[name];
  56837. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  56838. }
  56839. // Vector2
  56840. for (name in this._vectors2) {
  56841. this._effect.setVector2(name, this._vectors2[name]);
  56842. }
  56843. // Vector3
  56844. for (name in this._vectors3) {
  56845. this._effect.setVector3(name, this._vectors3[name]);
  56846. }
  56847. // Matrix
  56848. for (name in this._matrices) {
  56849. this._effect.setMatrix(name, this._matrices[name]);
  56850. }
  56851. if (!this._texture) {
  56852. return;
  56853. }
  56854. if (this.isCube) {
  56855. for (var face = 0; face < 6; face++) {
  56856. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  56857. // VBOs
  56858. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  56859. this._effect.setFloat("face", face);
  56860. // Clear
  56861. engine.clear(scene.clearColor, true, true, true);
  56862. // Draw order
  56863. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  56864. // Mipmaps
  56865. if (face === 5) {
  56866. engine.generateMipMapsForCubemap(this._texture);
  56867. }
  56868. }
  56869. }
  56870. else {
  56871. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  56872. // VBOs
  56873. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  56874. // Clear
  56875. engine.clear(scene.clearColor, true, true, true);
  56876. // Draw order
  56877. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  56878. }
  56879. // Unbind
  56880. engine.unBindFramebuffer(this._texture, this.isCube);
  56881. if (this.onGenerated) {
  56882. this.onGenerated();
  56883. }
  56884. };
  56885. ProceduralTexture.prototype.clone = function () {
  56886. var textureSize = this.getSize();
  56887. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  56888. // Base texture
  56889. newTexture.hasAlpha = this.hasAlpha;
  56890. newTexture.level = this.level;
  56891. // RenderTarget Texture
  56892. newTexture.coordinatesMode = this.coordinatesMode;
  56893. return newTexture;
  56894. };
  56895. ProceduralTexture.prototype.dispose = function () {
  56896. var scene = this.getScene();
  56897. if (!scene) {
  56898. return;
  56899. }
  56900. var index = scene._proceduralTextures.indexOf(this);
  56901. if (index >= 0) {
  56902. scene._proceduralTextures.splice(index, 1);
  56903. }
  56904. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  56905. if (vertexBuffer) {
  56906. vertexBuffer.dispose();
  56907. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  56908. }
  56909. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  56910. this._indexBuffer = null;
  56911. }
  56912. _super.prototype.dispose.call(this);
  56913. };
  56914. return ProceduralTexture;
  56915. }(BABYLON.Texture));
  56916. BABYLON.ProceduralTexture = ProceduralTexture;
  56917. })(BABYLON || (BABYLON = {}));
  56918. //# sourceMappingURL=babylon.proceduralTexture.js.map
  56919. var BABYLON;
  56920. (function (BABYLON) {
  56921. var CustomProceduralTexture = /** @class */ (function (_super) {
  56922. __extends(CustomProceduralTexture, _super);
  56923. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  56924. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  56925. _this._animate = true;
  56926. _this._time = 0;
  56927. _this._texturePath = texturePath;
  56928. //Try to load json
  56929. _this.loadJson(texturePath);
  56930. _this.refreshRate = 1;
  56931. return _this;
  56932. }
  56933. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  56934. var _this = this;
  56935. var noConfigFile = function () {
  56936. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  56937. try {
  56938. _this.setFragment(_this._texturePath);
  56939. }
  56940. catch (ex) {
  56941. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  56942. }
  56943. };
  56944. var configFileUrl = jsonUrl + "/config.json";
  56945. var xhr = new XMLHttpRequest();
  56946. xhr.open("GET", configFileUrl, true);
  56947. xhr.addEventListener("load", function () {
  56948. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  56949. try {
  56950. _this._config = JSON.parse(xhr.response);
  56951. _this.updateShaderUniforms();
  56952. _this.updateTextures();
  56953. _this.setFragment(_this._texturePath + "/custom");
  56954. _this._animate = _this._config.animate;
  56955. _this.refreshRate = _this._config.refreshrate;
  56956. }
  56957. catch (ex) {
  56958. noConfigFile();
  56959. }
  56960. }
  56961. else {
  56962. noConfigFile();
  56963. }
  56964. }, false);
  56965. xhr.addEventListener("error", function () {
  56966. noConfigFile();
  56967. }, false);
  56968. try {
  56969. xhr.send();
  56970. }
  56971. catch (ex) {
  56972. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  56973. }
  56974. };
  56975. CustomProceduralTexture.prototype.isReady = function () {
  56976. if (!_super.prototype.isReady.call(this)) {
  56977. return false;
  56978. }
  56979. for (var name in this._textures) {
  56980. var texture = this._textures[name];
  56981. if (!texture.isReady()) {
  56982. return false;
  56983. }
  56984. }
  56985. return true;
  56986. };
  56987. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  56988. var scene = this.getScene();
  56989. if (this._animate && scene) {
  56990. this._time += scene.getAnimationRatio() * 0.03;
  56991. this.updateShaderUniforms();
  56992. }
  56993. _super.prototype.render.call(this, useCameraPostProcess);
  56994. };
  56995. CustomProceduralTexture.prototype.updateTextures = function () {
  56996. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  56997. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  56998. }
  56999. };
  57000. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  57001. if (this._config) {
  57002. for (var j = 0; j < this._config.uniforms.length; j++) {
  57003. var uniform = this._config.uniforms[j];
  57004. switch (uniform.type) {
  57005. case "float":
  57006. this.setFloat(uniform.name, uniform.value);
  57007. break;
  57008. case "color3":
  57009. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  57010. break;
  57011. case "color4":
  57012. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  57013. break;
  57014. case "vector2":
  57015. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  57016. break;
  57017. case "vector3":
  57018. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  57019. break;
  57020. }
  57021. }
  57022. }
  57023. this.setFloat("time", this._time);
  57024. };
  57025. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  57026. get: function () {
  57027. return this._animate;
  57028. },
  57029. set: function (value) {
  57030. this._animate = value;
  57031. },
  57032. enumerable: true,
  57033. configurable: true
  57034. });
  57035. return CustomProceduralTexture;
  57036. }(BABYLON.ProceduralTexture));
  57037. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  57038. })(BABYLON || (BABYLON = {}));
  57039. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  57040. var BABYLON;
  57041. (function (BABYLON) {
  57042. var FreeCameraGamepadInput = /** @class */ (function () {
  57043. function FreeCameraGamepadInput() {
  57044. this.gamepadAngularSensibility = 200;
  57045. this.gamepadMoveSensibility = 40;
  57046. // private members
  57047. this._cameraTransform = BABYLON.Matrix.Identity();
  57048. this._deltaTransform = BABYLON.Vector3.Zero();
  57049. this._vector3 = BABYLON.Vector3.Zero();
  57050. this._vector2 = BABYLON.Vector2.Zero();
  57051. }
  57052. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  57053. var _this = this;
  57054. var manager = this.camera.getScene().gamepadManager;
  57055. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  57056. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  57057. // prioritize XBOX gamepads.
  57058. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  57059. _this.gamepad = gamepad;
  57060. }
  57061. }
  57062. });
  57063. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  57064. if (_this.gamepad === gamepad) {
  57065. _this.gamepad = null;
  57066. }
  57067. });
  57068. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  57069. };
  57070. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  57071. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  57072. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  57073. this.gamepad = null;
  57074. };
  57075. FreeCameraGamepadInput.prototype.checkInputs = function () {
  57076. if (this.gamepad && this.gamepad.leftStick) {
  57077. var camera = this.camera;
  57078. var LSValues = this.gamepad.leftStick;
  57079. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  57080. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  57081. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  57082. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  57083. var RSValues = this.gamepad.rightStick;
  57084. if (RSValues) {
  57085. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  57086. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  57087. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  57088. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  57089. }
  57090. else {
  57091. RSValues = { x: 0, y: 0 };
  57092. }
  57093. if (!camera.rotationQuaternion) {
  57094. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  57095. }
  57096. else {
  57097. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  57098. }
  57099. var speed = camera._computeLocalCameraSpeed() * 50.0;
  57100. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  57101. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  57102. camera.cameraDirection.addInPlace(this._deltaTransform);
  57103. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  57104. camera.cameraRotation.addInPlace(this._vector2);
  57105. }
  57106. };
  57107. FreeCameraGamepadInput.prototype.getClassName = function () {
  57108. return "FreeCameraGamepadInput";
  57109. };
  57110. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  57111. return "gamepad";
  57112. };
  57113. __decorate([
  57114. BABYLON.serialize()
  57115. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  57116. __decorate([
  57117. BABYLON.serialize()
  57118. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  57119. return FreeCameraGamepadInput;
  57120. }());
  57121. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  57122. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  57123. })(BABYLON || (BABYLON = {}));
  57124. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  57125. var BABYLON;
  57126. (function (BABYLON) {
  57127. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  57128. function ArcRotateCameraGamepadInput() {
  57129. this.gamepadRotationSensibility = 80;
  57130. this.gamepadMoveSensibility = 40;
  57131. }
  57132. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  57133. var _this = this;
  57134. var manager = this.camera.getScene().gamepadManager;
  57135. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  57136. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  57137. // prioritize XBOX gamepads.
  57138. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  57139. _this.gamepad = gamepad;
  57140. }
  57141. }
  57142. });
  57143. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  57144. if (_this.gamepad === gamepad) {
  57145. _this.gamepad = null;
  57146. }
  57147. });
  57148. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  57149. };
  57150. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  57151. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  57152. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  57153. this.gamepad = null;
  57154. };
  57155. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  57156. if (this.gamepad) {
  57157. var camera = this.camera;
  57158. var RSValues = this.gamepad.rightStick;
  57159. if (RSValues) {
  57160. if (RSValues.x != 0) {
  57161. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  57162. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  57163. camera.inertialAlphaOffset += normalizedRX;
  57164. }
  57165. }
  57166. if (RSValues.y != 0) {
  57167. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  57168. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  57169. camera.inertialBetaOffset += normalizedRY;
  57170. }
  57171. }
  57172. }
  57173. var LSValues = this.gamepad.leftStick;
  57174. if (LSValues && LSValues.y != 0) {
  57175. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  57176. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  57177. this.camera.inertialRadiusOffset -= normalizedLY;
  57178. }
  57179. }
  57180. }
  57181. };
  57182. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  57183. return "ArcRotateCameraGamepadInput";
  57184. };
  57185. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  57186. return "gamepad";
  57187. };
  57188. __decorate([
  57189. BABYLON.serialize()
  57190. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  57191. __decorate([
  57192. BABYLON.serialize()
  57193. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  57194. return ArcRotateCameraGamepadInput;
  57195. }());
  57196. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  57197. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  57198. })(BABYLON || (BABYLON = {}));
  57199. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  57200. var BABYLON;
  57201. (function (BABYLON) {
  57202. var GamepadManager = /** @class */ (function () {
  57203. function GamepadManager(_scene) {
  57204. var _this = this;
  57205. this._scene = _scene;
  57206. this._babylonGamepads = [];
  57207. this._oneGamepadConnected = false;
  57208. this._isMonitoring = false;
  57209. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  57210. if (!BABYLON.Tools.IsWindowObjectExist()) {
  57211. this._gamepadEventSupported = false;
  57212. }
  57213. else {
  57214. this._gamepadEventSupported = 'GamepadEvent' in window;
  57215. this._gamepadSupport = (navigator.getGamepads ||
  57216. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  57217. }
  57218. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  57219. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  57220. for (var i in _this._babylonGamepads) {
  57221. var gamepad = _this._babylonGamepads[i];
  57222. if (gamepad && gamepad._isConnected) {
  57223. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  57224. }
  57225. }
  57226. });
  57227. this._onGamepadConnectedEvent = function (evt) {
  57228. var gamepad = evt.gamepad;
  57229. if (gamepad.index in _this._babylonGamepads) {
  57230. if (_this._babylonGamepads[gamepad.index].isConnected) {
  57231. return;
  57232. }
  57233. }
  57234. var newGamepad;
  57235. if (_this._babylonGamepads[gamepad.index]) {
  57236. newGamepad = _this._babylonGamepads[gamepad.index];
  57237. newGamepad.browserGamepad = gamepad;
  57238. newGamepad._isConnected = true;
  57239. }
  57240. else {
  57241. newGamepad = _this._addNewGamepad(gamepad);
  57242. }
  57243. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  57244. _this._startMonitoringGamepads();
  57245. };
  57246. this._onGamepadDisconnectedEvent = function (evt) {
  57247. var gamepad = evt.gamepad;
  57248. // Remove the gamepad from the list of gamepads to monitor.
  57249. for (var i in _this._babylonGamepads) {
  57250. if (_this._babylonGamepads[i].index === gamepad.index) {
  57251. var disconnectedGamepad = _this._babylonGamepads[i];
  57252. disconnectedGamepad._isConnected = false;
  57253. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  57254. break;
  57255. }
  57256. }
  57257. };
  57258. if (this._gamepadSupport) {
  57259. //first add already-connected gamepads
  57260. this._updateGamepadObjects();
  57261. if (this._babylonGamepads.length) {
  57262. this._startMonitoringGamepads();
  57263. }
  57264. // Checking if the gamepad connected event is supported (like in Firefox)
  57265. if (this._gamepadEventSupported) {
  57266. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  57267. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  57268. }
  57269. else {
  57270. this._startMonitoringGamepads();
  57271. }
  57272. }
  57273. }
  57274. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  57275. get: function () {
  57276. return this._babylonGamepads;
  57277. },
  57278. enumerable: true,
  57279. configurable: true
  57280. });
  57281. GamepadManager.prototype.getGamepadByType = function (type) {
  57282. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  57283. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  57284. var gamepad = _a[_i];
  57285. if (gamepad && gamepad.type === type) {
  57286. return gamepad;
  57287. }
  57288. }
  57289. return null;
  57290. };
  57291. GamepadManager.prototype.dispose = function () {
  57292. if (this._gamepadEventSupported) {
  57293. if (this._onGamepadConnectedEvent) {
  57294. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  57295. }
  57296. if (this._onGamepadDisconnectedEvent) {
  57297. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  57298. }
  57299. this._onGamepadConnectedEvent = null;
  57300. this._onGamepadDisconnectedEvent = null;
  57301. }
  57302. this._babylonGamepads.forEach(function (gamepad) {
  57303. gamepad.dispose();
  57304. });
  57305. this.onGamepadConnectedObservable.clear();
  57306. this.onGamepadDisconnectedObservable.clear();
  57307. this._oneGamepadConnected = false;
  57308. this._stopMonitoringGamepads();
  57309. this._babylonGamepads = [];
  57310. };
  57311. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  57312. if (!this._oneGamepadConnected) {
  57313. this._oneGamepadConnected = true;
  57314. }
  57315. var newGamepad;
  57316. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  57317. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  57318. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  57319. }
  57320. else if (gamepad.pose) {
  57321. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  57322. }
  57323. else {
  57324. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  57325. }
  57326. this._babylonGamepads[newGamepad.index] = newGamepad;
  57327. return newGamepad;
  57328. };
  57329. GamepadManager.prototype._startMonitoringGamepads = function () {
  57330. if (!this._isMonitoring) {
  57331. this._isMonitoring = true;
  57332. //back-comp
  57333. if (!this._scene) {
  57334. this._checkGamepadsStatus();
  57335. }
  57336. }
  57337. };
  57338. GamepadManager.prototype._stopMonitoringGamepads = function () {
  57339. this._isMonitoring = false;
  57340. };
  57341. GamepadManager.prototype._checkGamepadsStatus = function () {
  57342. var _this = this;
  57343. // Hack to be compatible Chrome
  57344. this._updateGamepadObjects();
  57345. for (var i in this._babylonGamepads) {
  57346. var gamepad = this._babylonGamepads[i];
  57347. if (!gamepad || !gamepad.isConnected) {
  57348. continue;
  57349. }
  57350. gamepad.update();
  57351. }
  57352. if (this._isMonitoring && !this._scene) {
  57353. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  57354. }
  57355. };
  57356. // This function is called only on Chrome, which does not properly support
  57357. // connection/disconnection events and forces you to recopy again the gamepad object
  57358. GamepadManager.prototype._updateGamepadObjects = function () {
  57359. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  57360. for (var i = 0; i < gamepads.length; i++) {
  57361. if (gamepads[i]) {
  57362. if (!this._babylonGamepads[gamepads[i].index]) {
  57363. var newGamepad = this._addNewGamepad(gamepads[i]);
  57364. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  57365. }
  57366. else {
  57367. // Forced to copy again this object for Chrome for unknown reason
  57368. this._babylonGamepads[i].browserGamepad = gamepads[i];
  57369. if (!this._babylonGamepads[i].isConnected) {
  57370. this._babylonGamepads[i]._isConnected = true;
  57371. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  57372. }
  57373. }
  57374. }
  57375. }
  57376. };
  57377. return GamepadManager;
  57378. }());
  57379. BABYLON.GamepadManager = GamepadManager;
  57380. })(BABYLON || (BABYLON = {}));
  57381. //# sourceMappingURL=babylon.gamepadManager.js.map
  57382. var BABYLON;
  57383. (function (BABYLON) {
  57384. var StickValues = /** @class */ (function () {
  57385. function StickValues(x, y) {
  57386. this.x = x;
  57387. this.y = y;
  57388. }
  57389. return StickValues;
  57390. }());
  57391. BABYLON.StickValues = StickValues;
  57392. var Gamepad = /** @class */ (function () {
  57393. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  57394. if (leftStickX === void 0) { leftStickX = 0; }
  57395. if (leftStickY === void 0) { leftStickY = 1; }
  57396. if (rightStickX === void 0) { rightStickX = 2; }
  57397. if (rightStickY === void 0) { rightStickY = 3; }
  57398. this.id = id;
  57399. this.index = index;
  57400. this.browserGamepad = browserGamepad;
  57401. this._isConnected = true;
  57402. this._invertLeftStickY = false;
  57403. this.type = Gamepad.GAMEPAD;
  57404. this._leftStickAxisX = leftStickX;
  57405. this._leftStickAxisY = leftStickY;
  57406. this._rightStickAxisX = rightStickX;
  57407. this._rightStickAxisY = rightStickY;
  57408. if (this.browserGamepad.axes.length >= 2) {
  57409. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  57410. }
  57411. if (this.browserGamepad.axes.length >= 4) {
  57412. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  57413. }
  57414. }
  57415. Object.defineProperty(Gamepad.prototype, "isConnected", {
  57416. get: function () {
  57417. return this._isConnected;
  57418. },
  57419. enumerable: true,
  57420. configurable: true
  57421. });
  57422. Gamepad.prototype.onleftstickchanged = function (callback) {
  57423. this._onleftstickchanged = callback;
  57424. };
  57425. Gamepad.prototype.onrightstickchanged = function (callback) {
  57426. this._onrightstickchanged = callback;
  57427. };
  57428. Object.defineProperty(Gamepad.prototype, "leftStick", {
  57429. get: function () {
  57430. return this._leftStick;
  57431. },
  57432. set: function (newValues) {
  57433. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  57434. this._onleftstickchanged(newValues);
  57435. }
  57436. this._leftStick = newValues;
  57437. },
  57438. enumerable: true,
  57439. configurable: true
  57440. });
  57441. Object.defineProperty(Gamepad.prototype, "rightStick", {
  57442. get: function () {
  57443. return this._rightStick;
  57444. },
  57445. set: function (newValues) {
  57446. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  57447. this._onrightstickchanged(newValues);
  57448. }
  57449. this._rightStick = newValues;
  57450. },
  57451. enumerable: true,
  57452. configurable: true
  57453. });
  57454. Gamepad.prototype.update = function () {
  57455. if (this._leftStick) {
  57456. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  57457. if (this._invertLeftStickY) {
  57458. this.leftStick.y *= -1;
  57459. }
  57460. }
  57461. if (this._rightStick) {
  57462. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  57463. }
  57464. };
  57465. Gamepad.prototype.dispose = function () {
  57466. };
  57467. Gamepad.GAMEPAD = 0;
  57468. Gamepad.GENERIC = 1;
  57469. Gamepad.XBOX = 2;
  57470. Gamepad.POSE_ENABLED = 3;
  57471. return Gamepad;
  57472. }());
  57473. BABYLON.Gamepad = Gamepad;
  57474. var GenericPad = /** @class */ (function (_super) {
  57475. __extends(GenericPad, _super);
  57476. function GenericPad(id, index, browserGamepad) {
  57477. var _this = _super.call(this, id, index, browserGamepad) || this;
  57478. _this.onButtonDownObservable = new BABYLON.Observable();
  57479. _this.onButtonUpObservable = new BABYLON.Observable();
  57480. _this.type = Gamepad.GENERIC;
  57481. _this._buttons = new Array(browserGamepad.buttons.length);
  57482. return _this;
  57483. }
  57484. GenericPad.prototype.onbuttondown = function (callback) {
  57485. this._onbuttondown = callback;
  57486. };
  57487. GenericPad.prototype.onbuttonup = function (callback) {
  57488. this._onbuttonup = callback;
  57489. };
  57490. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  57491. if (newValue !== currentValue) {
  57492. if (newValue === 1) {
  57493. if (this._onbuttondown) {
  57494. this._onbuttondown(buttonIndex);
  57495. }
  57496. this.onButtonDownObservable.notifyObservers(buttonIndex);
  57497. }
  57498. if (newValue === 0) {
  57499. if (this._onbuttonup) {
  57500. this._onbuttonup(buttonIndex);
  57501. }
  57502. this.onButtonUpObservable.notifyObservers(buttonIndex);
  57503. }
  57504. }
  57505. return newValue;
  57506. };
  57507. GenericPad.prototype.update = function () {
  57508. _super.prototype.update.call(this);
  57509. for (var index = 0; index < this._buttons.length; index++) {
  57510. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  57511. }
  57512. };
  57513. GenericPad.prototype.dispose = function () {
  57514. _super.prototype.dispose.call(this);
  57515. this.onButtonDownObservable.clear();
  57516. this.onButtonUpObservable.clear();
  57517. };
  57518. return GenericPad;
  57519. }(Gamepad));
  57520. BABYLON.GenericPad = GenericPad;
  57521. })(BABYLON || (BABYLON = {}));
  57522. //# sourceMappingURL=babylon.gamepad.js.map
  57523. var BABYLON;
  57524. (function (BABYLON) {
  57525. var Xbox360Button;
  57526. (function (Xbox360Button) {
  57527. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  57528. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  57529. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  57530. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  57531. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  57532. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  57533. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  57534. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  57535. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  57536. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  57537. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  57538. var Xbox360Dpad;
  57539. (function (Xbox360Dpad) {
  57540. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  57541. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  57542. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  57543. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  57544. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  57545. var Xbox360Pad = /** @class */ (function (_super) {
  57546. __extends(Xbox360Pad, _super);
  57547. function Xbox360Pad(id, index, gamepad, xboxOne) {
  57548. if (xboxOne === void 0) { xboxOne = false; }
  57549. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  57550. _this._leftTrigger = 0;
  57551. _this._rightTrigger = 0;
  57552. _this.onButtonDownObservable = new BABYLON.Observable();
  57553. _this.onButtonUpObservable = new BABYLON.Observable();
  57554. _this.onPadDownObservable = new BABYLON.Observable();
  57555. _this.onPadUpObservable = new BABYLON.Observable();
  57556. _this._buttonA = 0;
  57557. _this._buttonB = 0;
  57558. _this._buttonX = 0;
  57559. _this._buttonY = 0;
  57560. _this._buttonBack = 0;
  57561. _this._buttonStart = 0;
  57562. _this._buttonLB = 0;
  57563. _this._buttonRB = 0;
  57564. _this._buttonLeftStick = 0;
  57565. _this._buttonRightStick = 0;
  57566. _this._dPadUp = 0;
  57567. _this._dPadDown = 0;
  57568. _this._dPadLeft = 0;
  57569. _this._dPadRight = 0;
  57570. _this._isXboxOnePad = false;
  57571. _this.type = BABYLON.Gamepad.XBOX;
  57572. _this._isXboxOnePad = xboxOne;
  57573. return _this;
  57574. }
  57575. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  57576. this._onlefttriggerchanged = callback;
  57577. };
  57578. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  57579. this._onrighttriggerchanged = callback;
  57580. };
  57581. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  57582. get: function () {
  57583. return this._leftTrigger;
  57584. },
  57585. set: function (newValue) {
  57586. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  57587. this._onlefttriggerchanged(newValue);
  57588. }
  57589. this._leftTrigger = newValue;
  57590. },
  57591. enumerable: true,
  57592. configurable: true
  57593. });
  57594. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  57595. get: function () {
  57596. return this._rightTrigger;
  57597. },
  57598. set: function (newValue) {
  57599. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  57600. this._onrighttriggerchanged(newValue);
  57601. }
  57602. this._rightTrigger = newValue;
  57603. },
  57604. enumerable: true,
  57605. configurable: true
  57606. });
  57607. Xbox360Pad.prototype.onbuttondown = function (callback) {
  57608. this._onbuttondown = callback;
  57609. };
  57610. Xbox360Pad.prototype.onbuttonup = function (callback) {
  57611. this._onbuttonup = callback;
  57612. };
  57613. Xbox360Pad.prototype.ondpaddown = function (callback) {
  57614. this._ondpaddown = callback;
  57615. };
  57616. Xbox360Pad.prototype.ondpadup = function (callback) {
  57617. this._ondpadup = callback;
  57618. };
  57619. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  57620. if (newValue !== currentValue) {
  57621. if (newValue === 1) {
  57622. if (this._onbuttondown) {
  57623. this._onbuttondown(buttonType);
  57624. }
  57625. this.onButtonDownObservable.notifyObservers(buttonType);
  57626. }
  57627. if (newValue === 0) {
  57628. if (this._onbuttonup) {
  57629. this._onbuttonup(buttonType);
  57630. }
  57631. this.onButtonUpObservable.notifyObservers(buttonType);
  57632. }
  57633. }
  57634. return newValue;
  57635. };
  57636. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  57637. if (newValue !== currentValue) {
  57638. if (newValue === 1) {
  57639. if (this._ondpaddown) {
  57640. this._ondpaddown(buttonType);
  57641. }
  57642. this.onPadDownObservable.notifyObservers(buttonType);
  57643. }
  57644. if (newValue === 0) {
  57645. if (this._ondpadup) {
  57646. this._ondpadup(buttonType);
  57647. }
  57648. this.onPadUpObservable.notifyObservers(buttonType);
  57649. }
  57650. }
  57651. return newValue;
  57652. };
  57653. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  57654. get: function () {
  57655. return this._buttonA;
  57656. },
  57657. set: function (value) {
  57658. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  57659. },
  57660. enumerable: true,
  57661. configurable: true
  57662. });
  57663. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  57664. get: function () {
  57665. return this._buttonB;
  57666. },
  57667. set: function (value) {
  57668. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  57669. },
  57670. enumerable: true,
  57671. configurable: true
  57672. });
  57673. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  57674. get: function () {
  57675. return this._buttonX;
  57676. },
  57677. set: function (value) {
  57678. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  57679. },
  57680. enumerable: true,
  57681. configurable: true
  57682. });
  57683. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  57684. get: function () {
  57685. return this._buttonY;
  57686. },
  57687. set: function (value) {
  57688. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  57689. },
  57690. enumerable: true,
  57691. configurable: true
  57692. });
  57693. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  57694. get: function () {
  57695. return this._buttonStart;
  57696. },
  57697. set: function (value) {
  57698. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  57699. },
  57700. enumerable: true,
  57701. configurable: true
  57702. });
  57703. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  57704. get: function () {
  57705. return this._buttonBack;
  57706. },
  57707. set: function (value) {
  57708. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  57709. },
  57710. enumerable: true,
  57711. configurable: true
  57712. });
  57713. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  57714. get: function () {
  57715. return this._buttonLB;
  57716. },
  57717. set: function (value) {
  57718. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  57719. },
  57720. enumerable: true,
  57721. configurable: true
  57722. });
  57723. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  57724. get: function () {
  57725. return this._buttonRB;
  57726. },
  57727. set: function (value) {
  57728. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  57729. },
  57730. enumerable: true,
  57731. configurable: true
  57732. });
  57733. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  57734. get: function () {
  57735. return this._buttonLeftStick;
  57736. },
  57737. set: function (value) {
  57738. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  57739. },
  57740. enumerable: true,
  57741. configurable: true
  57742. });
  57743. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  57744. get: function () {
  57745. return this._buttonRightStick;
  57746. },
  57747. set: function (value) {
  57748. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  57749. },
  57750. enumerable: true,
  57751. configurable: true
  57752. });
  57753. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  57754. get: function () {
  57755. return this._dPadUp;
  57756. },
  57757. set: function (value) {
  57758. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  57759. },
  57760. enumerable: true,
  57761. configurable: true
  57762. });
  57763. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  57764. get: function () {
  57765. return this._dPadDown;
  57766. },
  57767. set: function (value) {
  57768. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  57769. },
  57770. enumerable: true,
  57771. configurable: true
  57772. });
  57773. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  57774. get: function () {
  57775. return this._dPadLeft;
  57776. },
  57777. set: function (value) {
  57778. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  57779. },
  57780. enumerable: true,
  57781. configurable: true
  57782. });
  57783. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  57784. get: function () {
  57785. return this._dPadRight;
  57786. },
  57787. set: function (value) {
  57788. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  57789. },
  57790. enumerable: true,
  57791. configurable: true
  57792. });
  57793. Xbox360Pad.prototype.update = function () {
  57794. _super.prototype.update.call(this);
  57795. if (this._isXboxOnePad) {
  57796. this.buttonA = this.browserGamepad.buttons[0].value;
  57797. this.buttonB = this.browserGamepad.buttons[1].value;
  57798. this.buttonX = this.browserGamepad.buttons[2].value;
  57799. this.buttonY = this.browserGamepad.buttons[3].value;
  57800. this.buttonLB = this.browserGamepad.buttons[4].value;
  57801. this.buttonRB = this.browserGamepad.buttons[5].value;
  57802. this.leftTrigger = this.browserGamepad.axes[2];
  57803. this.rightTrigger = this.browserGamepad.axes[5];
  57804. this.buttonBack = this.browserGamepad.buttons[9].value;
  57805. this.buttonStart = this.browserGamepad.buttons[8].value;
  57806. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  57807. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  57808. this.dPadUp = this.browserGamepad.buttons[11].value;
  57809. this.dPadDown = this.browserGamepad.buttons[12].value;
  57810. this.dPadLeft = this.browserGamepad.buttons[13].value;
  57811. this.dPadRight = this.browserGamepad.buttons[14].value;
  57812. }
  57813. else {
  57814. this.buttonA = this.browserGamepad.buttons[0].value;
  57815. this.buttonB = this.browserGamepad.buttons[1].value;
  57816. this.buttonX = this.browserGamepad.buttons[2].value;
  57817. this.buttonY = this.browserGamepad.buttons[3].value;
  57818. this.buttonLB = this.browserGamepad.buttons[4].value;
  57819. this.buttonRB = this.browserGamepad.buttons[5].value;
  57820. this.leftTrigger = this.browserGamepad.buttons[6].value;
  57821. this.rightTrigger = this.browserGamepad.buttons[7].value;
  57822. this.buttonBack = this.browserGamepad.buttons[8].value;
  57823. this.buttonStart = this.browserGamepad.buttons[9].value;
  57824. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  57825. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  57826. this.dPadUp = this.browserGamepad.buttons[12].value;
  57827. this.dPadDown = this.browserGamepad.buttons[13].value;
  57828. this.dPadLeft = this.browserGamepad.buttons[14].value;
  57829. this.dPadRight = this.browserGamepad.buttons[15].value;
  57830. }
  57831. };
  57832. Xbox360Pad.prototype.dispose = function () {
  57833. _super.prototype.dispose.call(this);
  57834. this.onButtonDownObservable.clear();
  57835. this.onButtonUpObservable.clear();
  57836. this.onPadDownObservable.clear();
  57837. this.onPadUpObservable.clear();
  57838. };
  57839. return Xbox360Pad;
  57840. }(BABYLON.Gamepad));
  57841. BABYLON.Xbox360Pad = Xbox360Pad;
  57842. })(BABYLON || (BABYLON = {}));
  57843. //# sourceMappingURL=babylon.xboxGamepad.js.map
  57844. var BABYLON;
  57845. (function (BABYLON) {
  57846. var PoseEnabledControllerType;
  57847. (function (PoseEnabledControllerType) {
  57848. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  57849. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  57850. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  57851. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 3] = "GENERIC";
  57852. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  57853. var PoseEnabledControllerHelper = /** @class */ (function () {
  57854. function PoseEnabledControllerHelper() {
  57855. }
  57856. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  57857. // Oculus Touch
  57858. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  57859. return new BABYLON.OculusTouchController(vrGamepad);
  57860. }
  57861. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  57862. return new BABYLON.WindowsMotionController(vrGamepad);
  57863. }
  57864. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  57865. return new BABYLON.ViveController(vrGamepad);
  57866. }
  57867. else {
  57868. return new BABYLON.GenericController(vrGamepad);
  57869. }
  57870. };
  57871. return PoseEnabledControllerHelper;
  57872. }());
  57873. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  57874. var PoseEnabledController = /** @class */ (function (_super) {
  57875. __extends(PoseEnabledController, _super);
  57876. function PoseEnabledController(browserGamepad) {
  57877. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  57878. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  57879. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  57880. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  57881. // Represents device position and rotation in babylon space
  57882. _this.devicePosition = BABYLON.Vector3.Zero();
  57883. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  57884. _this.deviceScaleFactor = 1;
  57885. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  57886. _this._deviceToWorld = BABYLON.Matrix.Identity();
  57887. _this._workingMatrix = BABYLON.Matrix.Identity();
  57888. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  57889. _this.controllerType = PoseEnabledControllerType.GENERIC;
  57890. _this.position = BABYLON.Vector3.Zero();
  57891. _this.rotationQuaternion = new BABYLON.Quaternion();
  57892. _this._calculatedPosition = BABYLON.Vector3.Zero();
  57893. _this._calculatedRotation = new BABYLON.Quaternion();
  57894. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  57895. return _this;
  57896. }
  57897. PoseEnabledController.prototype.update = function () {
  57898. _super.prototype.update.call(this);
  57899. var pose = this.browserGamepad.pose;
  57900. this.updateFromDevice(pose);
  57901. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  57902. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  57903. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  57904. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  57905. if (this._mesh) {
  57906. this._mesh.position.copyFrom(this.devicePosition);
  57907. if (this._mesh.rotationQuaternion) {
  57908. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  57909. }
  57910. }
  57911. };
  57912. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  57913. if (poseData) {
  57914. this.rawPose = poseData;
  57915. if (poseData.position) {
  57916. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  57917. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  57918. this._deviceRoomPosition.z *= -1;
  57919. }
  57920. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  57921. this._calculatedPosition.addInPlace(this.position);
  57922. }
  57923. var pose = this.rawPose;
  57924. if (poseData.orientation && pose.orientation) {
  57925. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  57926. if (this._mesh) {
  57927. if (this._mesh.getScene().useRightHandedSystem) {
  57928. this._deviceRoomRotationQuaternion.z *= -1;
  57929. this._deviceRoomRotationQuaternion.w *= -1;
  57930. }
  57931. else {
  57932. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  57933. }
  57934. }
  57935. // if the camera is set, rotate to the camera's rotation
  57936. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  57937. }
  57938. }
  57939. };
  57940. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  57941. if (this._mesh) {
  57942. this._mesh.parent = null;
  57943. }
  57944. this._mesh = mesh;
  57945. if (this._poseControlledCamera) {
  57946. this._mesh.parent = this._poseControlledCamera;
  57947. }
  57948. if (!this._mesh.rotationQuaternion) {
  57949. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  57950. }
  57951. };
  57952. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  57953. this._poseControlledCamera = camera;
  57954. if (this._mesh) {
  57955. this._mesh.parent = this._poseControlledCamera;
  57956. }
  57957. };
  57958. PoseEnabledController.prototype.dispose = function () {
  57959. if (this._mesh) {
  57960. this._mesh.dispose();
  57961. }
  57962. this._mesh = null;
  57963. _super.prototype.dispose.call(this);
  57964. };
  57965. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  57966. get: function () {
  57967. return this._mesh;
  57968. },
  57969. enumerable: true,
  57970. configurable: true
  57971. });
  57972. PoseEnabledController.prototype.getForwardRay = function (length) {
  57973. if (length === void 0) { length = 100; }
  57974. if (!this.mesh) {
  57975. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  57976. }
  57977. var m = this.mesh.getWorldMatrix();
  57978. var origin = m.getTranslation();
  57979. var forward = new BABYLON.Vector3(0, 0, -1);
  57980. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  57981. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  57982. return new BABYLON.Ray(origin, direction, length);
  57983. };
  57984. return PoseEnabledController;
  57985. }(BABYLON.Gamepad));
  57986. BABYLON.PoseEnabledController = PoseEnabledController;
  57987. })(BABYLON || (BABYLON = {}));
  57988. //# sourceMappingURL=babylon.poseEnabledController.js.map
  57989. var BABYLON;
  57990. (function (BABYLON) {
  57991. var WebVRController = /** @class */ (function (_super) {
  57992. __extends(WebVRController, _super);
  57993. function WebVRController(vrGamepad) {
  57994. var _this = _super.call(this, vrGamepad) || this;
  57995. // Observables
  57996. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  57997. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  57998. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  57999. _this.onPadStateChangedObservable = new BABYLON.Observable();
  58000. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  58001. _this.pad = { x: 0, y: 0 };
  58002. // avoid GC, store state in a tmp object
  58003. _this._changes = {
  58004. pressChanged: false,
  58005. touchChanged: false,
  58006. valueChanged: false,
  58007. changed: false
  58008. };
  58009. _this._buttons = new Array(vrGamepad.buttons.length);
  58010. _this.hand = vrGamepad.hand;
  58011. return _this;
  58012. }
  58013. WebVRController.prototype.onButtonStateChange = function (callback) {
  58014. this._onButtonStateChange = callback;
  58015. };
  58016. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  58017. get: function () {
  58018. return this._defaultModel;
  58019. },
  58020. enumerable: true,
  58021. configurable: true
  58022. });
  58023. WebVRController.prototype.update = function () {
  58024. _super.prototype.update.call(this);
  58025. for (var index = 0; index < this._buttons.length; index++) {
  58026. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  58027. }
  58028. ;
  58029. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  58030. this.pad.x = this.leftStick.x;
  58031. this.pad.y = this.leftStick.y;
  58032. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  58033. }
  58034. };
  58035. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  58036. if (!newState) {
  58037. newState = {
  58038. pressed: false,
  58039. touched: false,
  58040. value: 0
  58041. };
  58042. }
  58043. if (!currentState) {
  58044. this._buttons[buttonIndex] = {
  58045. pressed: newState.pressed,
  58046. touched: newState.touched,
  58047. value: newState.value
  58048. };
  58049. return;
  58050. }
  58051. this._checkChanges(newState, currentState);
  58052. if (this._changes.changed) {
  58053. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  58054. this.handleButtonChange(buttonIndex, newState, this._changes);
  58055. }
  58056. this._buttons[buttonIndex].pressed = newState.pressed;
  58057. this._buttons[buttonIndex].touched = newState.touched;
  58058. // oculus triggers are never 0, thou not touched.
  58059. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  58060. };
  58061. WebVRController.prototype._checkChanges = function (newState, currentState) {
  58062. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  58063. this._changes.touchChanged = newState.touched !== currentState.touched;
  58064. this._changes.valueChanged = newState.value !== currentState.value;
  58065. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  58066. return this._changes;
  58067. };
  58068. WebVRController.prototype.dispose = function () {
  58069. _super.prototype.dispose.call(this);
  58070. this.onTriggerStateChangedObservable.clear();
  58071. this.onMainButtonStateChangedObservable.clear();
  58072. this.onSecondaryButtonStateChangedObservable.clear();
  58073. this.onPadStateChangedObservable.clear();
  58074. this.onPadValuesChangedObservable.clear();
  58075. };
  58076. return WebVRController;
  58077. }(BABYLON.PoseEnabledController));
  58078. BABYLON.WebVRController = WebVRController;
  58079. })(BABYLON || (BABYLON = {}));
  58080. //# sourceMappingURL=babylon.webVRController.js.map
  58081. var BABYLON;
  58082. (function (BABYLON) {
  58083. var OculusTouchController = /** @class */ (function (_super) {
  58084. __extends(OculusTouchController, _super);
  58085. function OculusTouchController(vrGamepad) {
  58086. var _this = _super.call(this, vrGamepad) || this;
  58087. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  58088. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  58089. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  58090. return _this;
  58091. }
  58092. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  58093. var _this = this;
  58094. var meshName;
  58095. // Hand
  58096. if (this.hand === 'left') {
  58097. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  58098. }
  58099. else {
  58100. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  58101. }
  58102. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  58103. /*
  58104. Parent Mesh name: oculus_touch_left
  58105. - body
  58106. - trigger
  58107. - thumbstick
  58108. - grip
  58109. - button_y
  58110. - button_x
  58111. - button_enter
  58112. */
  58113. _this._defaultModel = newMeshes[1];
  58114. _this.attachToMesh(_this._defaultModel);
  58115. if (meshLoaded) {
  58116. meshLoaded(_this._defaultModel);
  58117. }
  58118. });
  58119. };
  58120. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  58121. // helper getters for left and right hand.
  58122. get: function () {
  58123. if (this.hand === 'right') {
  58124. return this.onMainButtonStateChangedObservable;
  58125. }
  58126. else {
  58127. throw new Error('No A button on left hand');
  58128. }
  58129. },
  58130. enumerable: true,
  58131. configurable: true
  58132. });
  58133. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  58134. get: function () {
  58135. if (this.hand === 'right') {
  58136. return this.onSecondaryButtonStateChangedObservable;
  58137. }
  58138. else {
  58139. throw new Error('No B button on left hand');
  58140. }
  58141. },
  58142. enumerable: true,
  58143. configurable: true
  58144. });
  58145. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  58146. get: function () {
  58147. if (this.hand === 'left') {
  58148. return this.onMainButtonStateChangedObservable;
  58149. }
  58150. else {
  58151. throw new Error('No X button on right hand');
  58152. }
  58153. },
  58154. enumerable: true,
  58155. configurable: true
  58156. });
  58157. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  58158. get: function () {
  58159. if (this.hand === 'left') {
  58160. return this.onSecondaryButtonStateChangedObservable;
  58161. }
  58162. else {
  58163. throw new Error('No Y button on right hand');
  58164. }
  58165. },
  58166. enumerable: true,
  58167. configurable: true
  58168. });
  58169. /*
  58170. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  58171. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  58172. 2) secondary trigger (same)
  58173. 3) A (right) X (left), touch, pressed = value
  58174. 4) B / Y
  58175. 5) thumb rest
  58176. */
  58177. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  58178. var notifyObject = state; //{ state: state, changes: changes };
  58179. var triggerDirection = this.hand === 'right' ? -1 : 1;
  58180. switch (buttonIdx) {
  58181. case 0:
  58182. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  58183. return;
  58184. case 1:// index trigger
  58185. if (this._defaultModel) {
  58186. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  58187. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  58188. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  58189. }
  58190. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  58191. return;
  58192. case 2:// secondary trigger
  58193. if (this._defaultModel) {
  58194. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  58195. }
  58196. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  58197. return;
  58198. case 3:
  58199. if (this._defaultModel) {
  58200. if (notifyObject.pressed) {
  58201. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  58202. }
  58203. else {
  58204. (this._defaultModel.getChildren()[1]).position.y = 0;
  58205. }
  58206. }
  58207. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  58208. return;
  58209. case 4:
  58210. if (this._defaultModel) {
  58211. if (notifyObject.pressed) {
  58212. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  58213. }
  58214. else {
  58215. (this._defaultModel.getChildren()[2]).position.y = 0;
  58216. }
  58217. }
  58218. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  58219. return;
  58220. case 5:
  58221. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  58222. return;
  58223. }
  58224. };
  58225. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  58226. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  58227. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  58228. return OculusTouchController;
  58229. }(BABYLON.WebVRController));
  58230. BABYLON.OculusTouchController = OculusTouchController;
  58231. })(BABYLON || (BABYLON = {}));
  58232. //# sourceMappingURL=babylon.oculusTouchController.js.map
  58233. var BABYLON;
  58234. (function (BABYLON) {
  58235. var ViveController = /** @class */ (function (_super) {
  58236. __extends(ViveController, _super);
  58237. function ViveController(vrGamepad) {
  58238. var _this = _super.call(this, vrGamepad) || this;
  58239. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  58240. _this._invertLeftStickY = true;
  58241. return _this;
  58242. }
  58243. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  58244. var _this = this;
  58245. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  58246. /*
  58247. Parent Mesh name: ViveWand
  58248. - body
  58249. - r_gripper
  58250. - l_gripper
  58251. - menu_button
  58252. - system_button
  58253. - trackpad
  58254. - trigger
  58255. - LED
  58256. */
  58257. _this._defaultModel = newMeshes[1];
  58258. _this.attachToMesh(_this._defaultModel);
  58259. if (meshLoaded) {
  58260. meshLoaded(_this._defaultModel);
  58261. }
  58262. });
  58263. };
  58264. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  58265. get: function () {
  58266. return this.onMainButtonStateChangedObservable;
  58267. },
  58268. enumerable: true,
  58269. configurable: true
  58270. });
  58271. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  58272. get: function () {
  58273. return this.onMainButtonStateChangedObservable;
  58274. },
  58275. enumerable: true,
  58276. configurable: true
  58277. });
  58278. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  58279. get: function () {
  58280. return this.onSecondaryButtonStateChangedObservable;
  58281. },
  58282. enumerable: true,
  58283. configurable: true
  58284. });
  58285. /**
  58286. * Vive mapping:
  58287. * 0: touchpad
  58288. * 1: trigger
  58289. * 2: left AND right buttons
  58290. * 3: menu button
  58291. */
  58292. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  58293. var notifyObject = state; //{ state: state, changes: changes };
  58294. switch (buttonIdx) {
  58295. case 0:
  58296. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  58297. return;
  58298. case 1:// index trigger
  58299. if (this._defaultModel) {
  58300. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  58301. }
  58302. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  58303. return;
  58304. case 2:// left AND right button
  58305. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  58306. return;
  58307. case 3:
  58308. if (this._defaultModel) {
  58309. if (notifyObject.pressed) {
  58310. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  58311. }
  58312. else {
  58313. (this._defaultModel.getChildren()[2]).position.y = 0;
  58314. }
  58315. }
  58316. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  58317. return;
  58318. }
  58319. };
  58320. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  58321. ViveController.MODEL_FILENAME = 'wand.babylon';
  58322. return ViveController;
  58323. }(BABYLON.WebVRController));
  58324. BABYLON.ViveController = ViveController;
  58325. })(BABYLON || (BABYLON = {}));
  58326. //# sourceMappingURL=babylon.viveController.js.map
  58327. var BABYLON;
  58328. (function (BABYLON) {
  58329. var GenericController = /** @class */ (function (_super) {
  58330. __extends(GenericController, _super);
  58331. function GenericController(vrGamepad) {
  58332. return _super.call(this, vrGamepad) || this;
  58333. }
  58334. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  58335. var _this = this;
  58336. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  58337. _this._defaultModel = newMeshes[1];
  58338. _this.attachToMesh(_this._defaultModel);
  58339. if (meshLoaded) {
  58340. meshLoaded(_this._defaultModel);
  58341. }
  58342. });
  58343. };
  58344. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  58345. console.log("Button id: " + buttonIdx + "state: ");
  58346. console.dir(state);
  58347. };
  58348. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  58349. GenericController.MODEL_FILENAME = 'generic.babylon';
  58350. return GenericController;
  58351. }(BABYLON.WebVRController));
  58352. BABYLON.GenericController = GenericController;
  58353. })(BABYLON || (BABYLON = {}));
  58354. //# sourceMappingURL=babylon.genericController.js.map
  58355. var BABYLON;
  58356. (function (BABYLON) {
  58357. var LoadedMeshInfo = /** @class */ (function () {
  58358. function LoadedMeshInfo() {
  58359. this.buttonMeshes = {};
  58360. this.axisMeshes = {};
  58361. }
  58362. return LoadedMeshInfo;
  58363. }());
  58364. var WindowsMotionController = /** @class */ (function (_super) {
  58365. __extends(WindowsMotionController, _super);
  58366. function WindowsMotionController(vrGamepad) {
  58367. var _this = _super.call(this, vrGamepad) || this;
  58368. _this._mapping = {
  58369. // Semantic button names
  58370. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  58371. // A mapping of the button name to glTF model node name
  58372. // that should be transformed by button value.
  58373. buttonMeshNames: {
  58374. 'trigger': 'SELECT',
  58375. 'menu': 'MENU',
  58376. 'grip': 'GRASP',
  58377. 'thumbstick': 'THUMBSTICK_PRESS',
  58378. 'trackpad': 'TOUCHPAD_PRESS'
  58379. },
  58380. // This mapping is used to translate from the Motion Controller to Babylon semantics
  58381. buttonObservableNames: {
  58382. 'trigger': 'onTriggerStateChangedObservable',
  58383. 'menu': 'onSecondaryButtonStateChangedObservable',
  58384. 'grip': 'onMainButtonStateChangedObservable',
  58385. 'thumbstick': 'onPadStateChangedObservable',
  58386. 'trackpad': 'onTrackpadChangedObservable'
  58387. },
  58388. // A mapping of the axis name to glTF model node name
  58389. // that should be transformed by axis value.
  58390. // This array mirrors the browserGamepad.axes array, such that
  58391. // the mesh corresponding to axis 0 is in this array index 0.
  58392. axisMeshNames: [
  58393. 'THUMBSTICK_X',
  58394. 'THUMBSTICK_Y',
  58395. 'TOUCHPAD_TOUCH_X',
  58396. 'TOUCHPAD_TOUCH_Y'
  58397. ],
  58398. pointingPoseMeshName: 'POINTING_POSE'
  58399. };
  58400. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  58401. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  58402. _this.trackpad = { x: 0, y: 0 };
  58403. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  58404. _this._loadedMeshInfo = null;
  58405. return _this;
  58406. }
  58407. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  58408. get: function () {
  58409. return this.onTriggerStateChangedObservable;
  58410. },
  58411. enumerable: true,
  58412. configurable: true
  58413. });
  58414. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  58415. get: function () {
  58416. return this.onSecondaryButtonStateChangedObservable;
  58417. },
  58418. enumerable: true,
  58419. configurable: true
  58420. });
  58421. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  58422. get: function () {
  58423. return this.onMainButtonStateChangedObservable;
  58424. },
  58425. enumerable: true,
  58426. configurable: true
  58427. });
  58428. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  58429. get: function () {
  58430. return this.onPadStateChangedObservable;
  58431. },
  58432. enumerable: true,
  58433. configurable: true
  58434. });
  58435. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  58436. get: function () {
  58437. return this.onTrackpadChangedObservable;
  58438. },
  58439. enumerable: true,
  58440. configurable: true
  58441. });
  58442. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  58443. get: function () {
  58444. return this.onTrackpadValuesChangedObservable;
  58445. },
  58446. enumerable: true,
  58447. configurable: true
  58448. });
  58449. /**
  58450. * Called once per frame by the engine.
  58451. */
  58452. WindowsMotionController.prototype.update = function () {
  58453. _super.prototype.update.call(this);
  58454. // Only need to animate axes if there is a loaded mesh
  58455. if (this._loadedMeshInfo) {
  58456. if (this.browserGamepad.axes) {
  58457. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  58458. this.trackpad.x = this.browserGamepad["axes"][2];
  58459. this.trackpad.y = this.browserGamepad["axes"][3];
  58460. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  58461. }
  58462. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  58463. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  58464. }
  58465. }
  58466. }
  58467. };
  58468. /**
  58469. * Called once for each button that changed state since the last frame
  58470. * @param buttonIdx Which button index changed
  58471. * @param state New state of the button
  58472. * @param changes Which properties on the state changed since last frame
  58473. */
  58474. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  58475. var buttonName = this._mapping.buttons[buttonIdx];
  58476. if (!buttonName) {
  58477. return;
  58478. }
  58479. // Only emit events for buttons that we know how to map from index to name
  58480. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  58481. if (observable) {
  58482. observable.notifyObservers(state);
  58483. }
  58484. this.lerpButtonTransform(buttonName, state.value);
  58485. };
  58486. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  58487. // If there is no loaded mesh, there is nothing to transform.
  58488. if (!this._loadedMeshInfo) {
  58489. return;
  58490. }
  58491. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  58492. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  58493. return;
  58494. }
  58495. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  58496. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  58497. };
  58498. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  58499. if (!this._loadedMeshInfo) {
  58500. return;
  58501. }
  58502. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  58503. if (!meshInfo) {
  58504. return;
  58505. }
  58506. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  58507. return;
  58508. }
  58509. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  58510. var lerpValue = axisValue * 0.5 + 0.5;
  58511. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  58512. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  58513. };
  58514. /**
  58515. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  58516. * @param scene scene in which to add meshes
  58517. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  58518. */
  58519. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  58520. var _this = this;
  58521. if (forceDefault === void 0) { forceDefault = false; }
  58522. var path;
  58523. var filename;
  58524. // Checking if GLB loader is present
  58525. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  58526. // Determine the device specific folder based on the ID suffix
  58527. var device = 'default';
  58528. if (this.id && !forceDefault) {
  58529. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  58530. device = ((match && match[0]) || device);
  58531. }
  58532. // Hand
  58533. if (this.hand === 'left') {
  58534. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  58535. }
  58536. else {
  58537. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  58538. }
  58539. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  58540. }
  58541. else {
  58542. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  58543. path = BABYLON.GenericController.MODEL_BASE_URL;
  58544. filename = BABYLON.GenericController.MODEL_FILENAME;
  58545. }
  58546. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  58547. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  58548. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  58549. if (!_this._loadedMeshInfo) {
  58550. return;
  58551. }
  58552. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  58553. _this.attachToMesh(_this._defaultModel);
  58554. if (meshLoaded) {
  58555. meshLoaded(_this._defaultModel);
  58556. }
  58557. }, null, function (scene, message) {
  58558. BABYLON.Tools.Log(message);
  58559. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  58560. if (!forceDefault) {
  58561. _this.initControllerMesh(scene, meshLoaded, true);
  58562. }
  58563. });
  58564. };
  58565. /**
  58566. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  58567. * can be transformed by button presses and axes values, based on this._mapping.
  58568. *
  58569. * @param scene scene in which the meshes exist
  58570. * @param meshes list of meshes that make up the controller model to process
  58571. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  58572. */
  58573. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  58574. var loadedMeshInfo = null;
  58575. // Create a new mesh to contain the glTF hierarchy
  58576. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  58577. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  58578. var childMesh = null;
  58579. for (var i = 0; i < meshes.length; i++) {
  58580. var mesh = meshes[i];
  58581. if (!mesh.parent) {
  58582. // Exclude controller meshes from picking results
  58583. mesh.isPickable = false;
  58584. // Handle root node, attach to the new parentMesh
  58585. childMesh = mesh;
  58586. break;
  58587. }
  58588. }
  58589. if (childMesh) {
  58590. childMesh.setParent(parentMesh);
  58591. // Create our mesh info. Note that this method will always return non-null.
  58592. loadedMeshInfo = this.createMeshInfo(parentMesh);
  58593. }
  58594. else {
  58595. BABYLON.Tools.Warn('Could not find root node in model file.');
  58596. }
  58597. return loadedMeshInfo;
  58598. };
  58599. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  58600. var loadedMeshInfo = new LoadedMeshInfo();
  58601. var i;
  58602. loadedMeshInfo.rootNode = rootNode;
  58603. // Reset the caches
  58604. loadedMeshInfo.buttonMeshes = {};
  58605. loadedMeshInfo.axisMeshes = {};
  58606. // Button Meshes
  58607. for (i = 0; i < this._mapping.buttons.length; i++) {
  58608. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  58609. if (!buttonMeshName) {
  58610. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  58611. continue;
  58612. }
  58613. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  58614. if (!buttonMesh) {
  58615. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  58616. continue;
  58617. }
  58618. var buttonMeshInfo = {
  58619. index: i,
  58620. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  58621. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  58622. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  58623. };
  58624. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  58625. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  58626. }
  58627. else {
  58628. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  58629. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  58630. '(VALUE: ' + !!buttonMeshInfo.value +
  58631. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  58632. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  58633. ')');
  58634. }
  58635. }
  58636. // Axis Meshes
  58637. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  58638. var axisMeshName = this._mapping.axisMeshNames[i];
  58639. if (!axisMeshName) {
  58640. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  58641. continue;
  58642. }
  58643. var axisMesh = getChildByName(rootNode, axisMeshName);
  58644. if (!axisMesh) {
  58645. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  58646. continue;
  58647. }
  58648. var axisMeshInfo = {
  58649. index: i,
  58650. value: getImmediateChildByName(axisMesh, 'VALUE'),
  58651. min: getImmediateChildByName(axisMesh, 'MIN'),
  58652. max: getImmediateChildByName(axisMesh, 'MAX')
  58653. };
  58654. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  58655. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  58656. }
  58657. else {
  58658. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  58659. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  58660. '(VALUE: ' + !!axisMeshInfo.value +
  58661. ', MIN: ' + !!axisMeshInfo.min +
  58662. ', MAX:' + !!axisMeshInfo.max +
  58663. ')');
  58664. }
  58665. }
  58666. // Pointing Ray
  58667. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  58668. if (!loadedMeshInfo.pointingPoseNode) {
  58669. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  58670. }
  58671. return loadedMeshInfo;
  58672. // Look through all children recursively. This will return null if no mesh exists with the given name.
  58673. function getChildByName(node, name) {
  58674. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  58675. }
  58676. // Look through only immediate children. This will return null if no mesh exists with the given name.
  58677. function getImmediateChildByName(node, name) {
  58678. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  58679. }
  58680. };
  58681. WindowsMotionController.prototype.getForwardRay = function (length) {
  58682. if (length === void 0) { length = 100; }
  58683. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  58684. return _super.prototype.getForwardRay.call(this, length);
  58685. }
  58686. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  58687. var origin = m.getTranslation();
  58688. var forward = new BABYLON.Vector3(0, 0, -1);
  58689. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  58690. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  58691. return new BABYLON.Ray(origin, direction, length);
  58692. };
  58693. WindowsMotionController.prototype.dispose = function () {
  58694. _super.prototype.dispose.call(this);
  58695. this.onTrackpadChangedObservable.clear();
  58696. };
  58697. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  58698. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  58699. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  58700. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  58701. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  58702. return WindowsMotionController;
  58703. }(BABYLON.WebVRController));
  58704. BABYLON.WindowsMotionController = WindowsMotionController;
  58705. })(BABYLON || (BABYLON = {}));
  58706. //# sourceMappingURL=babylon.windowsMotionController.js.map
  58707. var BABYLON;
  58708. (function (BABYLON) {
  58709. var FollowCamera = /** @class */ (function (_super) {
  58710. __extends(FollowCamera, _super);
  58711. function FollowCamera(name, position, scene, lockedTarget) {
  58712. if (lockedTarget === void 0) { lockedTarget = null; }
  58713. var _this = _super.call(this, name, position, scene) || this;
  58714. _this.radius = 12;
  58715. _this.rotationOffset = 0;
  58716. _this.heightOffset = 4;
  58717. _this.cameraAcceleration = 0.05;
  58718. _this.maxCameraSpeed = 20;
  58719. _this.lockedTarget = lockedTarget;
  58720. return _this;
  58721. }
  58722. FollowCamera.prototype.getRadians = function (degrees) {
  58723. return degrees * Math.PI / 180;
  58724. };
  58725. FollowCamera.prototype.follow = function (cameraTarget) {
  58726. if (!cameraTarget)
  58727. return;
  58728. var yRotation;
  58729. if (cameraTarget.rotationQuaternion) {
  58730. var rotMatrix = new BABYLON.Matrix();
  58731. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  58732. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  58733. }
  58734. else {
  58735. yRotation = cameraTarget.rotation.y;
  58736. }
  58737. var radians = this.getRadians(this.rotationOffset) + yRotation;
  58738. var targetPosition = cameraTarget.getAbsolutePosition();
  58739. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  58740. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  58741. var dx = targetX - this.position.x;
  58742. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  58743. var dz = (targetZ) - this.position.z;
  58744. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  58745. var vy = dy * this.cameraAcceleration;
  58746. var vz = dz * this.cameraAcceleration * 2;
  58747. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  58748. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  58749. }
  58750. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  58751. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  58752. }
  58753. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  58754. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  58755. }
  58756. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  58757. this.setTarget(targetPosition);
  58758. };
  58759. FollowCamera.prototype._checkInputs = function () {
  58760. _super.prototype._checkInputs.call(this);
  58761. if (this.lockedTarget) {
  58762. this.follow(this.lockedTarget);
  58763. }
  58764. };
  58765. FollowCamera.prototype.getClassName = function () {
  58766. return "FollowCamera";
  58767. };
  58768. __decorate([
  58769. BABYLON.serialize()
  58770. ], FollowCamera.prototype, "radius", void 0);
  58771. __decorate([
  58772. BABYLON.serialize()
  58773. ], FollowCamera.prototype, "rotationOffset", void 0);
  58774. __decorate([
  58775. BABYLON.serialize()
  58776. ], FollowCamera.prototype, "heightOffset", void 0);
  58777. __decorate([
  58778. BABYLON.serialize()
  58779. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  58780. __decorate([
  58781. BABYLON.serialize()
  58782. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  58783. __decorate([
  58784. BABYLON.serializeAsMeshReference("lockedTargetId")
  58785. ], FollowCamera.prototype, "lockedTarget", void 0);
  58786. return FollowCamera;
  58787. }(BABYLON.TargetCamera));
  58788. BABYLON.FollowCamera = FollowCamera;
  58789. var ArcFollowCamera = /** @class */ (function (_super) {
  58790. __extends(ArcFollowCamera, _super);
  58791. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  58792. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  58793. _this.alpha = alpha;
  58794. _this.beta = beta;
  58795. _this.radius = radius;
  58796. _this.target = target;
  58797. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  58798. _this.follow();
  58799. return _this;
  58800. }
  58801. ArcFollowCamera.prototype.follow = function () {
  58802. if (!this.target) {
  58803. return;
  58804. }
  58805. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  58806. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  58807. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  58808. var targetPosition = this.target.getAbsolutePosition();
  58809. this.position = targetPosition.add(this._cartesianCoordinates);
  58810. this.setTarget(targetPosition);
  58811. };
  58812. ArcFollowCamera.prototype._checkInputs = function () {
  58813. _super.prototype._checkInputs.call(this);
  58814. this.follow();
  58815. };
  58816. ArcFollowCamera.prototype.getClassName = function () {
  58817. return "ArcFollowCamera";
  58818. };
  58819. return ArcFollowCamera;
  58820. }(BABYLON.TargetCamera));
  58821. BABYLON.ArcFollowCamera = ArcFollowCamera;
  58822. })(BABYLON || (BABYLON = {}));
  58823. //# sourceMappingURL=babylon.followCamera.js.map
  58824. var BABYLON;
  58825. (function (BABYLON) {
  58826. // We're mainly based on the logic defined into the FreeCamera code
  58827. var UniversalCamera = /** @class */ (function (_super) {
  58828. __extends(UniversalCamera, _super);
  58829. //-- end properties for backward compatibility for inputs
  58830. function UniversalCamera(name, position, scene) {
  58831. var _this = _super.call(this, name, position, scene) || this;
  58832. _this.inputs.addGamepad();
  58833. return _this;
  58834. }
  58835. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  58836. //-- Begin properties for backward compatibility for inputs
  58837. get: function () {
  58838. var gamepad = this.inputs.attached["gamepad"];
  58839. if (gamepad)
  58840. return gamepad.gamepadAngularSensibility;
  58841. return 0;
  58842. },
  58843. set: function (value) {
  58844. var gamepad = this.inputs.attached["gamepad"];
  58845. if (gamepad)
  58846. gamepad.gamepadAngularSensibility = value;
  58847. },
  58848. enumerable: true,
  58849. configurable: true
  58850. });
  58851. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  58852. get: function () {
  58853. var gamepad = this.inputs.attached["gamepad"];
  58854. if (gamepad)
  58855. return gamepad.gamepadMoveSensibility;
  58856. return 0;
  58857. },
  58858. set: function (value) {
  58859. var gamepad = this.inputs.attached["gamepad"];
  58860. if (gamepad)
  58861. gamepad.gamepadMoveSensibility = value;
  58862. },
  58863. enumerable: true,
  58864. configurable: true
  58865. });
  58866. UniversalCamera.prototype.getClassName = function () {
  58867. return "UniversalCamera";
  58868. };
  58869. return UniversalCamera;
  58870. }(BABYLON.TouchCamera));
  58871. BABYLON.UniversalCamera = UniversalCamera;
  58872. })(BABYLON || (BABYLON = {}));
  58873. //# sourceMappingURL=babylon.universalCamera.js.map
  58874. var BABYLON;
  58875. (function (BABYLON) {
  58876. // We're mainly based on the logic defined into the FreeCamera code
  58877. var GamepadCamera = /** @class */ (function (_super) {
  58878. __extends(GamepadCamera, _super);
  58879. //-- end properties for backward compatibility for inputs
  58880. function GamepadCamera(name, position, scene) {
  58881. return _super.call(this, name, position, scene) || this;
  58882. }
  58883. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  58884. //-- Begin properties for backward compatibility for inputs
  58885. get: function () {
  58886. var gamepad = this.inputs.attached["gamepad"];
  58887. if (gamepad)
  58888. return gamepad.gamepadAngularSensibility;
  58889. return 0;
  58890. },
  58891. set: function (value) {
  58892. var gamepad = this.inputs.attached["gamepad"];
  58893. if (gamepad)
  58894. gamepad.gamepadAngularSensibility = value;
  58895. },
  58896. enumerable: true,
  58897. configurable: true
  58898. });
  58899. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  58900. get: function () {
  58901. var gamepad = this.inputs.attached["gamepad"];
  58902. if (gamepad)
  58903. return gamepad.gamepadMoveSensibility;
  58904. return 0;
  58905. },
  58906. set: function (value) {
  58907. var gamepad = this.inputs.attached["gamepad"];
  58908. if (gamepad)
  58909. gamepad.gamepadMoveSensibility = value;
  58910. },
  58911. enumerable: true,
  58912. configurable: true
  58913. });
  58914. GamepadCamera.prototype.getClassName = function () {
  58915. return "GamepadCamera";
  58916. };
  58917. return GamepadCamera;
  58918. }(BABYLON.UniversalCamera));
  58919. BABYLON.GamepadCamera = GamepadCamera;
  58920. })(BABYLON || (BABYLON = {}));
  58921. //# sourceMappingURL=babylon.gamepadCamera.js.map
  58922. var BABYLON;
  58923. (function (BABYLON) {
  58924. var PostProcessRenderPipelineManager = /** @class */ (function () {
  58925. function PostProcessRenderPipelineManager() {
  58926. this._renderPipelines = {};
  58927. }
  58928. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  58929. this._renderPipelines[renderPipeline._name] = renderPipeline;
  58930. };
  58931. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  58932. if (unique === void 0) { unique = false; }
  58933. var renderPipeline = this._renderPipelines[renderPipelineName];
  58934. if (!renderPipeline) {
  58935. return;
  58936. }
  58937. renderPipeline._attachCameras(cameras, unique);
  58938. };
  58939. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  58940. var renderPipeline = this._renderPipelines[renderPipelineName];
  58941. if (!renderPipeline) {
  58942. return;
  58943. }
  58944. renderPipeline._detachCameras(cameras);
  58945. };
  58946. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  58947. var renderPipeline = this._renderPipelines[renderPipelineName];
  58948. if (!renderPipeline) {
  58949. return;
  58950. }
  58951. renderPipeline._enableEffect(renderEffectName, cameras);
  58952. };
  58953. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  58954. var renderPipeline = this._renderPipelines[renderPipelineName];
  58955. if (!renderPipeline) {
  58956. return;
  58957. }
  58958. renderPipeline._disableEffect(renderEffectName, cameras);
  58959. };
  58960. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  58961. var renderPipeline = this._renderPipelines[renderPipelineName];
  58962. if (!renderPipeline) {
  58963. return;
  58964. }
  58965. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  58966. };
  58967. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  58968. var renderPipeline = this._renderPipelines[renderPipelineName];
  58969. if (!renderPipeline) {
  58970. return;
  58971. }
  58972. renderPipeline._disableDisplayOnlyPass(cameras);
  58973. };
  58974. PostProcessRenderPipelineManager.prototype.update = function () {
  58975. for (var renderPipelineName in this._renderPipelines) {
  58976. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  58977. var pipeline = this._renderPipelines[renderPipelineName];
  58978. if (!pipeline.isSupported) {
  58979. pipeline.dispose();
  58980. delete this._renderPipelines[renderPipelineName];
  58981. }
  58982. else {
  58983. pipeline._update();
  58984. }
  58985. }
  58986. }
  58987. };
  58988. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  58989. for (var renderPipelineName in this._renderPipelines) {
  58990. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  58991. var pipeline = this._renderPipelines[renderPipelineName];
  58992. pipeline._rebuild();
  58993. }
  58994. }
  58995. };
  58996. PostProcessRenderPipelineManager.prototype.dispose = function () {
  58997. for (var renderPipelineName in this._renderPipelines) {
  58998. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  58999. var pipeline = this._renderPipelines[renderPipelineName];
  59000. pipeline.dispose();
  59001. }
  59002. }
  59003. };
  59004. return PostProcessRenderPipelineManager;
  59005. }());
  59006. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  59007. })(BABYLON || (BABYLON = {}));
  59008. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  59009. var BABYLON;
  59010. (function (BABYLON) {
  59011. var PostProcessRenderPass = /** @class */ (function () {
  59012. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  59013. this._refCount = 0;
  59014. this._name = name;
  59015. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  59016. this.setRenderList(renderList);
  59017. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  59018. this._renderTexture.onAfterRenderObservable.add(afterRender);
  59019. this._scene = scene;
  59020. this._renderList = renderList;
  59021. }
  59022. // private
  59023. PostProcessRenderPass.prototype._incRefCount = function () {
  59024. if (this._refCount === 0) {
  59025. this._scene.customRenderTargets.push(this._renderTexture);
  59026. }
  59027. return ++this._refCount;
  59028. };
  59029. PostProcessRenderPass.prototype._decRefCount = function () {
  59030. this._refCount--;
  59031. if (this._refCount <= 0) {
  59032. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  59033. }
  59034. return this._refCount;
  59035. };
  59036. PostProcessRenderPass.prototype._update = function () {
  59037. this.setRenderList(this._renderList);
  59038. };
  59039. // public
  59040. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  59041. this._renderTexture.renderList = renderList;
  59042. };
  59043. PostProcessRenderPass.prototype.getRenderTexture = function () {
  59044. return this._renderTexture;
  59045. };
  59046. return PostProcessRenderPass;
  59047. }());
  59048. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  59049. })(BABYLON || (BABYLON = {}));
  59050. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  59051. var BABYLON;
  59052. (function (BABYLON) {
  59053. var PostProcessRenderEffect = /** @class */ (function () {
  59054. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  59055. this._name = name;
  59056. this._singleInstance = singleInstance || true;
  59057. this._getPostProcess = getPostProcess;
  59058. this._cameras = {};
  59059. this._indicesForCamera = {};
  59060. this._postProcesses = {};
  59061. this._renderPasses = {};
  59062. this._renderEffectAsPasses = {};
  59063. }
  59064. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  59065. get: function () {
  59066. for (var index in this._postProcesses) {
  59067. if (!this._postProcesses[index].isSupported) {
  59068. return false;
  59069. }
  59070. }
  59071. return true;
  59072. },
  59073. enumerable: true,
  59074. configurable: true
  59075. });
  59076. PostProcessRenderEffect.prototype._update = function () {
  59077. for (var renderPassName in this._renderPasses) {
  59078. this._renderPasses[renderPassName]._update();
  59079. }
  59080. };
  59081. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  59082. this._renderPasses[renderPass._name] = renderPass;
  59083. this._linkParameters();
  59084. };
  59085. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  59086. delete this._renderPasses[renderPass._name];
  59087. this._linkParameters();
  59088. };
  59089. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  59090. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  59091. this._linkParameters();
  59092. };
  59093. PostProcessRenderEffect.prototype.getPass = function (passName) {
  59094. for (var renderPassName in this._renderPasses) {
  59095. if (renderPassName === passName) {
  59096. return this._renderPasses[passName];
  59097. }
  59098. }
  59099. return null;
  59100. };
  59101. PostProcessRenderEffect.prototype.emptyPasses = function () {
  59102. this._renderPasses = {};
  59103. this._linkParameters();
  59104. };
  59105. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  59106. var cameraKey;
  59107. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59108. if (!cams) {
  59109. return;
  59110. }
  59111. for (var i = 0; i < cams.length; i++) {
  59112. var camera = cams[i];
  59113. var cameraName = camera.name;
  59114. if (this._singleInstance) {
  59115. cameraKey = 0;
  59116. }
  59117. else {
  59118. cameraKey = cameraName;
  59119. }
  59120. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  59121. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  59122. if (!this._indicesForCamera[cameraName]) {
  59123. this._indicesForCamera[cameraName] = [];
  59124. }
  59125. this._indicesForCamera[cameraName].push(index);
  59126. if (!this._cameras[cameraName]) {
  59127. this._cameras[cameraName] = camera;
  59128. }
  59129. for (var passName in this._renderPasses) {
  59130. this._renderPasses[passName]._incRefCount();
  59131. }
  59132. }
  59133. this._linkParameters();
  59134. };
  59135. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  59136. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59137. if (!cams) {
  59138. return;
  59139. }
  59140. for (var i = 0; i < cams.length; i++) {
  59141. var camera = cams[i];
  59142. var cameraName = camera.name;
  59143. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  59144. if (this._cameras[cameraName]) {
  59145. //this._indicesForCamera.splice(index, 1);
  59146. this._cameras[cameraName] = null;
  59147. }
  59148. for (var passName in this._renderPasses) {
  59149. this._renderPasses[passName]._decRefCount();
  59150. }
  59151. }
  59152. };
  59153. PostProcessRenderEffect.prototype._enable = function (cameras) {
  59154. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59155. if (!cams) {
  59156. return;
  59157. }
  59158. for (var i = 0; i < cams.length; i++) {
  59159. var camera = cams[i];
  59160. var cameraName = camera.name;
  59161. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  59162. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  59163. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  59164. }
  59165. }
  59166. for (var passName in this._renderPasses) {
  59167. this._renderPasses[passName]._incRefCount();
  59168. }
  59169. }
  59170. };
  59171. PostProcessRenderEffect.prototype._disable = function (cameras) {
  59172. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59173. if (!cams) {
  59174. return;
  59175. }
  59176. for (var i = 0; i < cams.length; i++) {
  59177. var camera = cams[i];
  59178. var cameraName = camera.Name;
  59179. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  59180. for (var passName in this._renderPasses) {
  59181. this._renderPasses[passName]._decRefCount();
  59182. }
  59183. }
  59184. };
  59185. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  59186. if (this._singleInstance) {
  59187. return this._postProcesses[0];
  59188. }
  59189. else {
  59190. if (!camera) {
  59191. return null;
  59192. }
  59193. return this._postProcesses[camera.name];
  59194. }
  59195. };
  59196. PostProcessRenderEffect.prototype._linkParameters = function () {
  59197. var _this = this;
  59198. for (var index in this._postProcesses) {
  59199. if (this.applyParameters) {
  59200. this.applyParameters(this._postProcesses[index]);
  59201. }
  59202. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  59203. _this._linkTextures(effect);
  59204. });
  59205. }
  59206. };
  59207. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  59208. for (var renderPassName in this._renderPasses) {
  59209. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  59210. }
  59211. for (var renderEffectName in this._renderEffectAsPasses) {
  59212. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  59213. }
  59214. };
  59215. return PostProcessRenderEffect;
  59216. }());
  59217. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  59218. })(BABYLON || (BABYLON = {}));
  59219. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  59220. var BABYLON;
  59221. (function (BABYLON) {
  59222. var PostProcessRenderPipeline = /** @class */ (function () {
  59223. function PostProcessRenderPipeline(engine, name) {
  59224. this._engine = engine;
  59225. this._name = name;
  59226. this._renderEffects = {};
  59227. this._renderEffectsForIsolatedPass = new Array();
  59228. this._cameras = [];
  59229. }
  59230. PostProcessRenderPipeline.prototype.getClassName = function () {
  59231. return "PostProcessRenderPipeline";
  59232. };
  59233. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  59234. get: function () {
  59235. for (var renderEffectName in this._renderEffects) {
  59236. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59237. if (!this._renderEffects[renderEffectName].isSupported) {
  59238. return false;
  59239. }
  59240. }
  59241. }
  59242. return true;
  59243. },
  59244. enumerable: true,
  59245. configurable: true
  59246. });
  59247. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  59248. this._renderEffects[renderEffect._name] = renderEffect;
  59249. };
  59250. // private
  59251. PostProcessRenderPipeline.prototype._rebuild = function () {
  59252. };
  59253. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  59254. var renderEffects = this._renderEffects[renderEffectName];
  59255. if (!renderEffects) {
  59256. return;
  59257. }
  59258. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  59259. };
  59260. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  59261. var renderEffects = this._renderEffects[renderEffectName];
  59262. if (!renderEffects) {
  59263. return;
  59264. }
  59265. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  59266. };
  59267. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  59268. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59269. if (!cams) {
  59270. return;
  59271. }
  59272. var indicesToDelete = [];
  59273. var i;
  59274. for (i = 0; i < cams.length; i++) {
  59275. var camera = cams[i];
  59276. var cameraName = camera.name;
  59277. if (this._cameras.indexOf(camera) === -1) {
  59278. this._cameras[cameraName] = camera;
  59279. }
  59280. else if (unique) {
  59281. indicesToDelete.push(i);
  59282. }
  59283. }
  59284. for (i = 0; i < indicesToDelete.length; i++) {
  59285. cameras.splice(indicesToDelete[i], 1);
  59286. }
  59287. for (var renderEffectName in this._renderEffects) {
  59288. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59289. this._renderEffects[renderEffectName]._attachCameras(cams);
  59290. }
  59291. }
  59292. };
  59293. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  59294. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59295. if (!cams) {
  59296. return;
  59297. }
  59298. for (var renderEffectName in this._renderEffects) {
  59299. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59300. this._renderEffects[renderEffectName]._detachCameras(cams);
  59301. }
  59302. }
  59303. for (var i = 0; i < cams.length; i++) {
  59304. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  59305. }
  59306. };
  59307. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  59308. var _this = this;
  59309. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59310. if (!cams) {
  59311. return;
  59312. }
  59313. var pass = null;
  59314. var renderEffectName;
  59315. for (renderEffectName in this._renderEffects) {
  59316. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59317. pass = this._renderEffects[renderEffectName].getPass(passName);
  59318. if (pass != null) {
  59319. break;
  59320. }
  59321. }
  59322. }
  59323. if (pass === null) {
  59324. return;
  59325. }
  59326. for (renderEffectName in this._renderEffects) {
  59327. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59328. this._renderEffects[renderEffectName]._disable(cams);
  59329. }
  59330. }
  59331. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  59332. for (var i = 0; i < cams.length; i++) {
  59333. var camera = cams[i];
  59334. var cameraName = camera.name;
  59335. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, undefined, _this._engine, true); });
  59336. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  59337. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  59338. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  59339. }
  59340. };
  59341. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  59342. var _this = this;
  59343. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59344. if (!cams) {
  59345. return;
  59346. }
  59347. for (var i = 0; i < cams.length; i++) {
  59348. var camera = cams[i];
  59349. var cameraName = camera.name;
  59350. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, undefined, _this._engine, true); });
  59351. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  59352. }
  59353. for (var renderEffectName in this._renderEffects) {
  59354. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59355. this._renderEffects[renderEffectName]._enable(cams);
  59356. }
  59357. }
  59358. };
  59359. PostProcessRenderPipeline.prototype._update = function () {
  59360. for (var renderEffectName in this._renderEffects) {
  59361. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59362. this._renderEffects[renderEffectName]._update();
  59363. }
  59364. }
  59365. for (var i = 0; i < this._cameras.length; i++) {
  59366. var cameraName = this._cameras[i].name;
  59367. if (this._renderEffectsForIsolatedPass[cameraName]) {
  59368. this._renderEffectsForIsolatedPass[cameraName]._update();
  59369. }
  59370. }
  59371. };
  59372. PostProcessRenderPipeline.prototype._reset = function () {
  59373. this._renderEffects = {};
  59374. this._renderEffectsForIsolatedPass = new Array();
  59375. };
  59376. PostProcessRenderPipeline.prototype.dispose = function () {
  59377. // Must be implemented by children
  59378. };
  59379. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  59380. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  59381. __decorate([
  59382. BABYLON.serialize()
  59383. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  59384. return PostProcessRenderPipeline;
  59385. }());
  59386. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  59387. })(BABYLON || (BABYLON = {}));
  59388. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  59389. var BABYLON;
  59390. (function (BABYLON) {
  59391. var DepthRenderer = /** @class */ (function () {
  59392. function DepthRenderer(scene, type) {
  59393. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  59394. var _this = this;
  59395. this._scene = scene;
  59396. var engine = scene.getEngine();
  59397. // Render target
  59398. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  59399. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59400. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59401. this._depthMap.refreshRate = 1;
  59402. this._depthMap.renderParticles = false;
  59403. this._depthMap.renderList = null;
  59404. // set default depth value to 1.0 (far away)
  59405. this._depthMap.onClearObservable.add(function (engine) {
  59406. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  59407. });
  59408. // Custom render function
  59409. var renderSubMesh = function (subMesh) {
  59410. var mesh = subMesh.getRenderingMesh();
  59411. var scene = _this._scene;
  59412. var engine = scene.getEngine();
  59413. var material = subMesh.getMaterial();
  59414. if (!material) {
  59415. return;
  59416. }
  59417. // Culling and reverse (right handed system)
  59418. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  59419. // Managing instances
  59420. var batch = mesh._getInstancesRenderList(subMesh._id);
  59421. if (batch.mustReturn) {
  59422. return;
  59423. }
  59424. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  59425. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  59426. engine.enableEffect(_this._effect);
  59427. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  59428. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  59429. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  59430. // Alpha test
  59431. if (material && material.needAlphaTesting()) {
  59432. var alphaTexture = material.getAlphaTestTexture();
  59433. if (alphaTexture) {
  59434. _this._effect.setTexture("diffuseSampler", alphaTexture);
  59435. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  59436. }
  59437. }
  59438. // Bones
  59439. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59440. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  59441. }
  59442. // Draw
  59443. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  59444. }
  59445. };
  59446. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  59447. var index;
  59448. if (depthOnlySubMeshes.length) {
  59449. engine.setColorWrite(false);
  59450. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  59451. renderSubMesh(depthOnlySubMeshes.data[index]);
  59452. }
  59453. engine.setColorWrite(true);
  59454. }
  59455. for (index = 0; index < opaqueSubMeshes.length; index++) {
  59456. renderSubMesh(opaqueSubMeshes.data[index]);
  59457. }
  59458. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  59459. renderSubMesh(alphaTestSubMeshes.data[index]);
  59460. }
  59461. };
  59462. }
  59463. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  59464. var material = subMesh.getMaterial();
  59465. if (material.disableDepthWrite) {
  59466. return false;
  59467. }
  59468. var defines = [];
  59469. var attribs = [BABYLON.VertexBuffer.PositionKind];
  59470. var mesh = subMesh.getMesh();
  59471. // Alpha test
  59472. if (material && material.needAlphaTesting()) {
  59473. defines.push("#define ALPHATEST");
  59474. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59475. attribs.push(BABYLON.VertexBuffer.UVKind);
  59476. defines.push("#define UV1");
  59477. }
  59478. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  59479. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  59480. defines.push("#define UV2");
  59481. }
  59482. }
  59483. // Bones
  59484. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59485. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59486. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59487. if (mesh.numBoneInfluencers > 4) {
  59488. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59489. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59490. }
  59491. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59492. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  59493. }
  59494. else {
  59495. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59496. }
  59497. // Instances
  59498. if (useInstances) {
  59499. defines.push("#define INSTANCES");
  59500. attribs.push("world0");
  59501. attribs.push("world1");
  59502. attribs.push("world2");
  59503. attribs.push("world3");
  59504. }
  59505. // Get correct effect
  59506. var join = defines.join("\n");
  59507. if (this._cachedDefines !== join) {
  59508. this._cachedDefines = join;
  59509. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  59510. }
  59511. return this._effect.isReady();
  59512. };
  59513. DepthRenderer.prototype.getDepthMap = function () {
  59514. return this._depthMap;
  59515. };
  59516. // Methods
  59517. DepthRenderer.prototype.dispose = function () {
  59518. this._depthMap.dispose();
  59519. };
  59520. return DepthRenderer;
  59521. }());
  59522. BABYLON.DepthRenderer = DepthRenderer;
  59523. })(BABYLON || (BABYLON = {}));
  59524. //# sourceMappingURL=babylon.depthRenderer.js.map
  59525. var BABYLON;
  59526. (function (BABYLON) {
  59527. var SSAORenderingPipeline = /** @class */ (function (_super) {
  59528. __extends(SSAORenderingPipeline, _super);
  59529. /**
  59530. * @constructor
  59531. * @param {string} name - The rendering pipeline name
  59532. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  59533. * @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 }
  59534. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  59535. */
  59536. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  59537. var _this = _super.call(this, scene.getEngine(), name) || this;
  59538. // Members
  59539. /**
  59540. * The PassPostProcess id in the pipeline that contains the original scene color
  59541. * @type {string}
  59542. */
  59543. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  59544. /**
  59545. * The SSAO PostProcess id in the pipeline
  59546. * @type {string}
  59547. */
  59548. _this.SSAORenderEffect = "SSAORenderEffect";
  59549. /**
  59550. * The horizontal blur PostProcess id in the pipeline
  59551. * @type {string}
  59552. */
  59553. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  59554. /**
  59555. * The vertical blur PostProcess id in the pipeline
  59556. * @type {string}
  59557. */
  59558. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  59559. /**
  59560. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  59561. * @type {string}
  59562. */
  59563. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  59564. /**
  59565. * The output strength of the SSAO post-process. Default value is 1.0.
  59566. * @type {number}
  59567. */
  59568. _this.totalStrength = 1.0;
  59569. /**
  59570. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  59571. * @type {number}
  59572. */
  59573. _this.radius = 0.0001;
  59574. /**
  59575. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  59576. * Must not be equal to fallOff and superior to fallOff.
  59577. * Default value is 0.975
  59578. * @type {number}
  59579. */
  59580. _this.area = 0.0075;
  59581. /**
  59582. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  59583. * Must not be equal to area and inferior to area.
  59584. * Default value is 0.0
  59585. * @type {number}
  59586. */
  59587. _this.fallOff = 0.000001;
  59588. /**
  59589. * The base color of the SSAO post-process
  59590. * The final result is "base + ssao" between [0, 1]
  59591. * @type {number}
  59592. */
  59593. _this.base = 0.5;
  59594. _this._firstUpdate = true;
  59595. _this._scene = scene;
  59596. // Set up assets
  59597. _this._createRandomTexture();
  59598. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  59599. var ssaoRatio = ratio.ssaoRatio || ratio;
  59600. var combineRatio = ratio.combineRatio || ratio;
  59601. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  59602. _this._createSSAOPostProcess(ssaoRatio);
  59603. _this._createBlurPostProcess(ssaoRatio);
  59604. _this._createSSAOCombinePostProcess(combineRatio);
  59605. // Set up pipeline
  59606. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  59607. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  59608. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  59609. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  59610. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  59611. // Finish
  59612. scene.postProcessRenderPipelineManager.addPipeline(_this);
  59613. if (cameras)
  59614. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  59615. return _this;
  59616. }
  59617. // Public Methods
  59618. /**
  59619. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  59620. */
  59621. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  59622. if (disableDepthRender === void 0) { disableDepthRender = false; }
  59623. for (var i = 0; i < this._scene.cameras.length; i++) {
  59624. var camera = this._scene.cameras[i];
  59625. this._originalColorPostProcess.dispose(camera);
  59626. this._ssaoPostProcess.dispose(camera);
  59627. this._blurHPostProcess.dispose(camera);
  59628. this._blurVPostProcess.dispose(camera);
  59629. this._ssaoCombinePostProcess.dispose(camera);
  59630. }
  59631. this._randomTexture.dispose();
  59632. if (disableDepthRender)
  59633. this._scene.disableDepthRenderer();
  59634. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  59635. _super.prototype.dispose.call(this);
  59636. };
  59637. // Private Methods
  59638. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  59639. var _this = this;
  59640. var size = 16;
  59641. 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);
  59642. 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);
  59643. this._blurHPostProcess.onActivateObservable.add(function () {
  59644. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  59645. _this._blurHPostProcess.kernel = size * dw;
  59646. });
  59647. this._blurVPostProcess.onActivateObservable.add(function () {
  59648. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  59649. _this._blurVPostProcess.kernel = size * dw;
  59650. });
  59651. };
  59652. SSAORenderingPipeline.prototype._rebuild = function () {
  59653. this._firstUpdate = true;
  59654. _super.prototype._rebuild.call(this);
  59655. };
  59656. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  59657. var _this = this;
  59658. var numSamples = 16;
  59659. var sampleSphere = [
  59660. 0.5381, 0.1856, -0.4319,
  59661. 0.1379, 0.2486, 0.4430,
  59662. 0.3371, 0.5679, -0.0057,
  59663. -0.6999, -0.0451, -0.0019,
  59664. 0.0689, -0.1598, -0.8547,
  59665. 0.0560, 0.0069, -0.1843,
  59666. -0.0146, 0.1402, 0.0762,
  59667. 0.0100, -0.1924, -0.0344,
  59668. -0.3577, -0.5301, -0.4358,
  59669. -0.3169, 0.1063, 0.0158,
  59670. 0.0103, -0.5869, 0.0046,
  59671. -0.0897, -0.4940, 0.3287,
  59672. 0.7119, -0.0154, -0.0918,
  59673. -0.0533, 0.0596, -0.5411,
  59674. 0.0352, -0.0631, 0.5460,
  59675. -0.4776, 0.2847, -0.0271
  59676. ];
  59677. var samplesFactor = 1.0 / numSamples;
  59678. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  59679. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  59680. "area", "fallOff", "base", "range", "viewport"
  59681. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  59682. this._ssaoPostProcess.onApply = function (effect) {
  59683. if (_this._firstUpdate) {
  59684. effect.setArray3("sampleSphere", sampleSphere);
  59685. effect.setFloat("samplesFactor", samplesFactor);
  59686. effect.setFloat("randTextureTiles", 4.0);
  59687. }
  59688. effect.setFloat("totalStrength", _this.totalStrength);
  59689. effect.setFloat("radius", _this.radius);
  59690. effect.setFloat("area", _this.area);
  59691. effect.setFloat("fallOff", _this.fallOff);
  59692. effect.setFloat("base", _this.base);
  59693. effect.setTexture("textureSampler", _this._depthTexture);
  59694. effect.setTexture("randomSampler", _this._randomTexture);
  59695. };
  59696. };
  59697. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  59698. var _this = this;
  59699. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  59700. this._ssaoCombinePostProcess.onApply = function (effect) {
  59701. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  59702. };
  59703. };
  59704. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  59705. var size = 512;
  59706. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  59707. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  59708. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  59709. var context = this._randomTexture.getContext();
  59710. var rand = function (min, max) {
  59711. return Math.random() * (max - min) + min;
  59712. };
  59713. var randVector = BABYLON.Vector3.Zero();
  59714. for (var x = 0; x < size; x++) {
  59715. for (var y = 0; y < size; y++) {
  59716. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  59717. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  59718. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  59719. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  59720. context.fillRect(x, y, 1, 1);
  59721. }
  59722. }
  59723. this._randomTexture.update(false);
  59724. };
  59725. __decorate([
  59726. BABYLON.serialize()
  59727. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  59728. __decorate([
  59729. BABYLON.serialize()
  59730. ], SSAORenderingPipeline.prototype, "radius", void 0);
  59731. __decorate([
  59732. BABYLON.serialize()
  59733. ], SSAORenderingPipeline.prototype, "area", void 0);
  59734. __decorate([
  59735. BABYLON.serialize()
  59736. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  59737. __decorate([
  59738. BABYLON.serialize()
  59739. ], SSAORenderingPipeline.prototype, "base", void 0);
  59740. return SSAORenderingPipeline;
  59741. }(BABYLON.PostProcessRenderPipeline));
  59742. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  59743. })(BABYLON || (BABYLON = {}));
  59744. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  59745. var BABYLON;
  59746. (function (BABYLON) {
  59747. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  59748. __extends(SSAO2RenderingPipeline, _super);
  59749. /**
  59750. * @constructor
  59751. * @param {string} name - The rendering pipeline name
  59752. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  59753. * @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 }
  59754. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  59755. */
  59756. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  59757. var _this = _super.call(this, scene.getEngine(), name) || this;
  59758. // Members
  59759. /**
  59760. * The PassPostProcess id in the pipeline that contains the original scene color
  59761. * @type {string}
  59762. */
  59763. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  59764. /**
  59765. * The SSAO PostProcess id in the pipeline
  59766. * @type {string}
  59767. */
  59768. _this.SSAORenderEffect = "SSAORenderEffect";
  59769. /**
  59770. * The horizontal blur PostProcess id in the pipeline
  59771. * @type {string}
  59772. */
  59773. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  59774. /**
  59775. * The vertical blur PostProcess id in the pipeline
  59776. * @type {string}
  59777. */
  59778. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  59779. /**
  59780. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  59781. * @type {string}
  59782. */
  59783. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  59784. /**
  59785. * The output strength of the SSAO post-process. Default value is 1.0.
  59786. * @type {number}
  59787. */
  59788. _this.totalStrength = 1.0;
  59789. /**
  59790. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  59791. * @type {number}
  59792. */
  59793. _this.maxZ = 100.0;
  59794. /**
  59795. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  59796. * @type {number}
  59797. */
  59798. _this.minZAspect = 0.2;
  59799. /**
  59800. * Number of samples used for the SSAO calculations. Default value is 8
  59801. * @type {number}
  59802. */
  59803. _this._samples = 8;
  59804. /**
  59805. * Are we using bilateral blur ?
  59806. * @type {boolean}
  59807. */
  59808. _this._expensiveBlur = true;
  59809. /**
  59810. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  59811. * @type {number}
  59812. */
  59813. _this.radius = 2.0;
  59814. /**
  59815. * The base color of the SSAO post-process
  59816. * The final result is "base + ssao" between [0, 1]
  59817. * @type {number}
  59818. */
  59819. _this.base = 0.1;
  59820. _this._firstUpdate = true;
  59821. _this._scene = scene;
  59822. if (!_this.isSupported) {
  59823. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  59824. return _this;
  59825. }
  59826. var ssaoRatio = ratio.ssaoRatio || ratio;
  59827. var blurRatio = ratio.blurRatio || ratio;
  59828. // Set up assets
  59829. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  59830. _this._createRandomTexture();
  59831. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  59832. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  59833. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  59834. _this._createSSAOPostProcess(1.0);
  59835. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  59836. _this._createSSAOCombinePostProcess(blurRatio);
  59837. // Set up pipeline
  59838. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  59839. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  59840. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  59841. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  59842. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  59843. // Finish
  59844. scene.postProcessRenderPipelineManager.addPipeline(_this);
  59845. if (cameras)
  59846. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  59847. return _this;
  59848. }
  59849. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  59850. get: function () {
  59851. return this._samples;
  59852. },
  59853. set: function (n) {
  59854. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  59855. this._samples = n;
  59856. this._sampleSphere = this._generateHemisphere();
  59857. this._firstUpdate = true;
  59858. },
  59859. enumerable: true,
  59860. configurable: true
  59861. });
  59862. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  59863. get: function () {
  59864. return this._expensiveBlur;
  59865. },
  59866. set: function (b) {
  59867. 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"]);
  59868. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  59869. this._expensiveBlur = b;
  59870. this._firstUpdate = true;
  59871. },
  59872. enumerable: true,
  59873. configurable: true
  59874. });
  59875. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  59876. /**
  59877. * Support test.
  59878. * @type {boolean}
  59879. */
  59880. get: function () {
  59881. var engine = BABYLON.Engine.LastCreatedEngine;
  59882. if (!engine) {
  59883. return false;
  59884. }
  59885. return engine.getCaps().drawBuffersExtension;
  59886. },
  59887. enumerable: true,
  59888. configurable: true
  59889. });
  59890. // Public Methods
  59891. /**
  59892. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  59893. */
  59894. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  59895. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  59896. for (var i = 0; i < this._scene.cameras.length; i++) {
  59897. var camera = this._scene.cameras[i];
  59898. this._originalColorPostProcess.dispose(camera);
  59899. this._ssaoPostProcess.dispose(camera);
  59900. this._blurHPostProcess.dispose(camera);
  59901. this._blurVPostProcess.dispose(camera);
  59902. this._ssaoCombinePostProcess.dispose(camera);
  59903. }
  59904. this._randomTexture.dispose();
  59905. if (disableGeometryBufferRenderer)
  59906. this._scene.disableGeometryBufferRenderer();
  59907. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  59908. _super.prototype.dispose.call(this);
  59909. };
  59910. // Private Methods
  59911. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  59912. var _this = this;
  59913. this._samplerOffsets = [];
  59914. var expensive = this.expensiveBlur;
  59915. for (var i = -8; i < 8; i++) {
  59916. this._samplerOffsets.push(i * 2 + 0.5);
  59917. }
  59918. 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");
  59919. this._blurHPostProcess.onApply = function (effect) {
  59920. if (!_this._scene.activeCamera) {
  59921. return;
  59922. }
  59923. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  59924. effect.setFloat("near", _this._scene.activeCamera.minZ);
  59925. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  59926. effect.setFloat("radius", _this.radius);
  59927. effect.setTexture("depthSampler", _this._depthTexture);
  59928. if (_this._firstUpdate) {
  59929. effect.setArray("samplerOffsets", _this._samplerOffsets);
  59930. }
  59931. };
  59932. 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");
  59933. this._blurVPostProcess.onApply = function (effect) {
  59934. if (!_this._scene.activeCamera) {
  59935. return;
  59936. }
  59937. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  59938. effect.setFloat("near", _this._scene.activeCamera.minZ);
  59939. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  59940. effect.setFloat("radius", _this.radius);
  59941. effect.setTexture("depthSampler", _this._depthTexture);
  59942. if (_this._firstUpdate) {
  59943. effect.setArray("samplerOffsets", _this._samplerOffsets);
  59944. _this._firstUpdate = false;
  59945. }
  59946. };
  59947. };
  59948. SSAO2RenderingPipeline.prototype._rebuild = function () {
  59949. this._firstUpdate = true;
  59950. _super.prototype._rebuild.call(this);
  59951. };
  59952. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  59953. var numSamples = this.samples;
  59954. var result = [];
  59955. var vector, scale;
  59956. var rand = function (min, max) {
  59957. return Math.random() * (max - min) + min;
  59958. };
  59959. var i = 0;
  59960. while (i < numSamples) {
  59961. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  59962. vector.normalize();
  59963. scale = i / numSamples;
  59964. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  59965. vector.scaleInPlace(scale);
  59966. result.push(vector.x, vector.y, vector.z);
  59967. i++;
  59968. }
  59969. return result;
  59970. };
  59971. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  59972. var _this = this;
  59973. var numSamples = this.samples;
  59974. this._sampleSphere = this._generateHemisphere();
  59975. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  59976. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  59977. "base", "range", "projection", "near", "far", "texelSize",
  59978. "xViewport", "yViewport", "maxZ", "minZAspect"
  59979. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  59980. this._ssaoPostProcess.onApply = function (effect) {
  59981. if (_this._firstUpdate) {
  59982. effect.setArray3("sampleSphere", _this._sampleSphere);
  59983. effect.setFloat("randTextureTiles", 4.0);
  59984. }
  59985. if (!_this._scene.activeCamera) {
  59986. return;
  59987. }
  59988. effect.setFloat("samplesFactor", 1 / _this.samples);
  59989. effect.setFloat("totalStrength", _this.totalStrength);
  59990. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  59991. effect.setFloat("radius", _this.radius);
  59992. effect.setFloat("maxZ", _this.maxZ);
  59993. effect.setFloat("minZAspect", _this.minZAspect);
  59994. effect.setFloat("base", _this.base);
  59995. effect.setFloat("near", _this._scene.activeCamera.minZ);
  59996. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  59997. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  59998. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  59999. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  60000. effect.setTexture("textureSampler", _this._depthTexture);
  60001. effect.setTexture("normalSampler", _this._normalTexture);
  60002. effect.setTexture("randomSampler", _this._randomTexture);
  60003. };
  60004. };
  60005. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  60006. var _this = this;
  60007. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  60008. this._ssaoCombinePostProcess.onApply = function (effect) {
  60009. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  60010. };
  60011. };
  60012. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  60013. var size = 512;
  60014. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  60015. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60016. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60017. var context = this._randomTexture.getContext();
  60018. var rand = function (min, max) {
  60019. return Math.random() * (max - min) + min;
  60020. };
  60021. var randVector = BABYLON.Vector3.Zero();
  60022. for (var x = 0; x < size; x++) {
  60023. for (var y = 0; y < size; y++) {
  60024. randVector.x = rand(0.0, 1.0);
  60025. randVector.y = rand(0.0, 1.0);
  60026. randVector.z = 0.0;
  60027. randVector.normalize();
  60028. randVector.scaleInPlace(255);
  60029. randVector.x = Math.floor(randVector.x);
  60030. randVector.y = Math.floor(randVector.y);
  60031. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  60032. context.fillRect(x, y, 1, 1);
  60033. }
  60034. }
  60035. this._randomTexture.update(false);
  60036. };
  60037. __decorate([
  60038. BABYLON.serialize()
  60039. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  60040. __decorate([
  60041. BABYLON.serialize()
  60042. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  60043. __decorate([
  60044. BABYLON.serialize()
  60045. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  60046. __decorate([
  60047. BABYLON.serialize("samples")
  60048. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  60049. __decorate([
  60050. BABYLON.serialize("expensiveBlur")
  60051. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  60052. __decorate([
  60053. BABYLON.serialize()
  60054. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  60055. __decorate([
  60056. BABYLON.serialize()
  60057. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  60058. return SSAO2RenderingPipeline;
  60059. }(BABYLON.PostProcessRenderPipeline));
  60060. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  60061. })(BABYLON || (BABYLON = {}));
  60062. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  60063. // BABYLON.JS Chromatic Aberration GLSL Shader
  60064. // Author: Olivier Guyot
  60065. // Separates very slightly R, G and B colors on the edges of the screen
  60066. // Inspired by Francois Tarlier & Martins Upitis
  60067. var BABYLON;
  60068. (function (BABYLON) {
  60069. var LensRenderingPipeline = /** @class */ (function (_super) {
  60070. __extends(LensRenderingPipeline, _super);
  60071. /**
  60072. * @constructor
  60073. *
  60074. * Effect parameters are as follow:
  60075. * {
  60076. * chromatic_aberration: number; // from 0 to x (1 for realism)
  60077. * edge_blur: number; // from 0 to x (1 for realism)
  60078. * distortion: number; // from 0 to x (1 for realism)
  60079. * grain_amount: number; // from 0 to 1
  60080. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  60081. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  60082. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  60083. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  60084. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  60085. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  60086. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  60087. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  60088. * }
  60089. * Note: if an effect parameter is unset, effect is disabled
  60090. *
  60091. * @param {string} name - The rendering pipeline name
  60092. * @param {object} parameters - An object containing all parameters (see above)
  60093. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  60094. * @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)
  60095. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  60096. */
  60097. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  60098. if (ratio === void 0) { ratio = 1.0; }
  60099. var _this = _super.call(this, scene.getEngine(), name) || this;
  60100. // Lens effects can be of the following:
  60101. // - chromatic aberration (slight shift of RGB colors)
  60102. // - blur on the edge of the lens
  60103. // - lens distortion
  60104. // - depth-of-field blur & highlights enhancing
  60105. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  60106. // - grain effect (noise or custom texture)
  60107. // Two additional texture samplers are needed:
  60108. // - depth map (for depth-of-field)
  60109. // - grain texture
  60110. /**
  60111. * The chromatic aberration PostProcess id in the pipeline
  60112. * @type {string}
  60113. */
  60114. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  60115. /**
  60116. * The highlights enhancing PostProcess id in the pipeline
  60117. * @type {string}
  60118. */
  60119. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  60120. /**
  60121. * The depth-of-field PostProcess id in the pipeline
  60122. * @type {string}
  60123. */
  60124. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  60125. _this._scene = scene;
  60126. // Fetch texture samplers
  60127. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  60128. if (parameters.grain_texture) {
  60129. _this._grainTexture = parameters.grain_texture;
  60130. }
  60131. else {
  60132. _this._createGrainTexture();
  60133. }
  60134. // save parameters
  60135. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  60136. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  60137. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  60138. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  60139. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  60140. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  60141. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  60142. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  60143. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  60144. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  60145. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  60146. // Create effects
  60147. _this._createChromaticAberrationPostProcess(ratio);
  60148. _this._createHighlightsPostProcess(ratio);
  60149. _this._createDepthOfFieldPostProcess(ratio / 4);
  60150. // Set up pipeline
  60151. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  60152. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  60153. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  60154. if (_this._highlightsGain === -1) {
  60155. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  60156. }
  60157. // Finish
  60158. scene.postProcessRenderPipelineManager.addPipeline(_this);
  60159. if (cameras) {
  60160. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  60161. }
  60162. return _this;
  60163. }
  60164. // public methods (self explanatory)
  60165. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  60166. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  60167. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  60168. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  60169. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  60170. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  60171. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  60172. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  60173. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  60174. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  60175. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  60176. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  60177. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  60178. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  60179. };
  60180. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  60181. this._highlightsPostProcess.updateEffect();
  60182. };
  60183. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  60184. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  60185. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  60186. this._highlightsGain = amount;
  60187. };
  60188. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  60189. if (this._highlightsGain === -1) {
  60190. this._highlightsGain = 1.0;
  60191. }
  60192. this._highlightsThreshold = amount;
  60193. };
  60194. LensRenderingPipeline.prototype.disableHighlights = function () {
  60195. this._highlightsGain = -1;
  60196. };
  60197. /**
  60198. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  60199. */
  60200. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  60201. if (disableDepthRender === void 0) { disableDepthRender = false; }
  60202. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  60203. this._chromaticAberrationPostProcess = null;
  60204. this._highlightsPostProcess = null;
  60205. this._depthOfFieldPostProcess = null;
  60206. this._grainTexture.dispose();
  60207. if (disableDepthRender)
  60208. this._scene.disableDepthRenderer();
  60209. };
  60210. // colors shifting and distortion
  60211. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  60212. var _this = this;
  60213. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  60214. [], // samplers
  60215. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  60216. this._chromaticAberrationPostProcess.onApply = function (effect) {
  60217. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  60218. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  60219. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  60220. };
  60221. };
  60222. // highlights enhancing
  60223. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  60224. var _this = this;
  60225. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  60226. [], // samplers
  60227. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  60228. this._highlightsPostProcess.onApply = function (effect) {
  60229. effect.setFloat('gain', _this._highlightsGain);
  60230. effect.setFloat('threshold', _this._highlightsThreshold);
  60231. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  60232. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  60233. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  60234. };
  60235. };
  60236. // colors shifting and distortion
  60237. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  60238. var _this = this;
  60239. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  60240. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  60241. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  60242. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  60243. this._depthOfFieldPostProcess.onApply = function (effect) {
  60244. effect.setTexture("depthSampler", _this._depthTexture);
  60245. effect.setTexture("grainSampler", _this._grainTexture);
  60246. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  60247. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  60248. effect.setFloat('grain_amount', _this._grainAmount);
  60249. effect.setBool('blur_noise', _this._blurNoise);
  60250. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  60251. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  60252. effect.setFloat('distortion', _this._distortion);
  60253. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  60254. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  60255. effect.setFloat('aperture', _this._dofAperture);
  60256. effect.setFloat('darken', _this._dofDarken);
  60257. effect.setFloat('edge_blur', _this._edgeBlur);
  60258. effect.setBool('highlights', (_this._highlightsGain !== -1));
  60259. if (_this._scene.activeCamera) {
  60260. effect.setFloat('near', _this._scene.activeCamera.minZ);
  60261. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  60262. }
  60263. };
  60264. };
  60265. // creates a black and white random noise texture, 512x512
  60266. LensRenderingPipeline.prototype._createGrainTexture = function () {
  60267. var size = 512;
  60268. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60269. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60270. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60271. var context = this._grainTexture.getContext();
  60272. var rand = function (min, max) {
  60273. return Math.random() * (max - min) + min;
  60274. };
  60275. var value;
  60276. for (var x = 0; x < size; x++) {
  60277. for (var y = 0; y < size; y++) {
  60278. value = Math.floor(rand(0.42, 0.58) * 255);
  60279. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  60280. context.fillRect(x, y, 1, 1);
  60281. }
  60282. }
  60283. this._grainTexture.update(false);
  60284. };
  60285. return LensRenderingPipeline;
  60286. }(BABYLON.PostProcessRenderPipeline));
  60287. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  60288. })(BABYLON || (BABYLON = {}));
  60289. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  60290. var BABYLON;
  60291. (function (BABYLON) {
  60292. var StandardRenderingPipeline = /** @class */ (function (_super) {
  60293. __extends(StandardRenderingPipeline, _super);
  60294. /**
  60295. * @constructor
  60296. * @param {string} name - The rendering pipeline name
  60297. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  60298. * @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)
  60299. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  60300. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  60301. */
  60302. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  60303. if (originalPostProcess === void 0) { originalPostProcess = null; }
  60304. var _this = _super.call(this, scene.getEngine(), name) || this;
  60305. _this.downSampleX4PostProcess = null;
  60306. _this.brightPassPostProcess = null;
  60307. _this.blurHPostProcesses = [];
  60308. _this.blurVPostProcesses = [];
  60309. _this.textureAdderPostProcess = null;
  60310. _this.volumetricLightPostProcess = null;
  60311. _this.volumetricLightSmoothXPostProcess = null;
  60312. _this.volumetricLightSmoothYPostProcess = null;
  60313. _this.volumetricLightMergePostProces = null;
  60314. _this.volumetricLightFinalPostProcess = null;
  60315. _this.luminancePostProcess = null;
  60316. _this.luminanceDownSamplePostProcesses = [];
  60317. _this.hdrPostProcess = null;
  60318. _this.textureAdderFinalPostProcess = null;
  60319. _this.lensFlareFinalPostProcess = null;
  60320. _this.hdrFinalPostProcess = null;
  60321. _this.lensFlarePostProcess = null;
  60322. _this.lensFlareComposePostProcess = null;
  60323. _this.motionBlurPostProcess = null;
  60324. _this.depthOfFieldPostProcess = null;
  60325. // Values
  60326. _this.brightThreshold = 1.0;
  60327. _this.blurWidth = 512.0;
  60328. _this.horizontalBlur = false;
  60329. _this.exposure = 1.0;
  60330. _this.lensTexture = null;
  60331. _this.volumetricLightCoefficient = 0.2;
  60332. _this.volumetricLightPower = 4.0;
  60333. _this.volumetricLightBlurScale = 64.0;
  60334. _this.sourceLight = null;
  60335. _this.hdrMinimumLuminance = 1.0;
  60336. _this.hdrDecreaseRate = 0.5;
  60337. _this.hdrIncreaseRate = 0.5;
  60338. _this.lensColorTexture = null;
  60339. _this.lensFlareStrength = 20.0;
  60340. _this.lensFlareGhostDispersal = 1.4;
  60341. _this.lensFlareHaloWidth = 0.7;
  60342. _this.lensFlareDistortionStrength = 16.0;
  60343. _this.lensStarTexture = null;
  60344. _this.lensFlareDirtTexture = null;
  60345. _this.depthOfFieldDistance = 10.0;
  60346. _this.depthOfFieldBlurWidth = 64.0;
  60347. _this.motionStrength = 1.0;
  60348. // IAnimatable
  60349. _this.animations = [];
  60350. _this._currentDepthOfFieldSource = null;
  60351. _this._hdrCurrentLuminance = 1.0;
  60352. // Getters and setters
  60353. _this._bloomEnabled = true;
  60354. _this._depthOfFieldEnabled = false;
  60355. _this._vlsEnabled = false;
  60356. _this._lensFlareEnabled = false;
  60357. _this._hdrEnabled = false;
  60358. _this._motionBlurEnabled = false;
  60359. _this._motionBlurSamples = 64.0;
  60360. _this._volumetricLightStepsCount = 50.0;
  60361. _this._cameras = cameras || [];
  60362. // Initialize
  60363. _this._scene = scene;
  60364. _this._basePostProcess = originalPostProcess;
  60365. _this._ratio = ratio;
  60366. // Misc
  60367. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60368. // Finish
  60369. scene.postProcessRenderPipelineManager.addPipeline(_this);
  60370. _this._buildPipeline();
  60371. return _this;
  60372. }
  60373. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  60374. get: function () {
  60375. return this._bloomEnabled;
  60376. },
  60377. set: function (enabled) {
  60378. if (this._bloomEnabled === enabled) {
  60379. return;
  60380. }
  60381. this._bloomEnabled = enabled;
  60382. this._buildPipeline();
  60383. },
  60384. enumerable: true,
  60385. configurable: true
  60386. });
  60387. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  60388. get: function () {
  60389. return this._depthOfFieldEnabled;
  60390. },
  60391. set: function (enabled) {
  60392. if (this._depthOfFieldEnabled === enabled) {
  60393. return;
  60394. }
  60395. this._depthOfFieldEnabled = enabled;
  60396. this._buildPipeline();
  60397. },
  60398. enumerable: true,
  60399. configurable: true
  60400. });
  60401. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  60402. get: function () {
  60403. return this._lensFlareEnabled;
  60404. },
  60405. set: function (enabled) {
  60406. if (this._lensFlareEnabled === enabled) {
  60407. return;
  60408. }
  60409. this._lensFlareEnabled = enabled;
  60410. this._buildPipeline();
  60411. },
  60412. enumerable: true,
  60413. configurable: true
  60414. });
  60415. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  60416. get: function () {
  60417. return this._hdrEnabled;
  60418. },
  60419. set: function (enabled) {
  60420. if (this._hdrEnabled === enabled) {
  60421. return;
  60422. }
  60423. this._hdrEnabled = enabled;
  60424. this._buildPipeline();
  60425. },
  60426. enumerable: true,
  60427. configurable: true
  60428. });
  60429. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  60430. get: function () {
  60431. return this._vlsEnabled;
  60432. },
  60433. set: function (enabled) {
  60434. if (this._vlsEnabled === enabled) {
  60435. return;
  60436. }
  60437. if (enabled) {
  60438. var geometry = this._scene.enableGeometryBufferRenderer();
  60439. if (!geometry) {
  60440. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  60441. return;
  60442. }
  60443. }
  60444. this._vlsEnabled = enabled;
  60445. this._buildPipeline();
  60446. },
  60447. enumerable: true,
  60448. configurable: true
  60449. });
  60450. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  60451. get: function () {
  60452. return this._motionBlurEnabled;
  60453. },
  60454. set: function (enabled) {
  60455. if (this._motionBlurEnabled === enabled) {
  60456. return;
  60457. }
  60458. this._motionBlurEnabled = enabled;
  60459. this._buildPipeline();
  60460. },
  60461. enumerable: true,
  60462. configurable: true
  60463. });
  60464. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  60465. get: function () {
  60466. return this._volumetricLightStepsCount;
  60467. },
  60468. set: function (count) {
  60469. if (this.volumetricLightPostProcess) {
  60470. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  60471. }
  60472. this._volumetricLightStepsCount = count;
  60473. },
  60474. enumerable: true,
  60475. configurable: true
  60476. });
  60477. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  60478. get: function () {
  60479. return this._motionBlurSamples;
  60480. },
  60481. set: function (samples) {
  60482. if (this.motionBlurPostProcess) {
  60483. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  60484. }
  60485. this._motionBlurSamples = samples;
  60486. },
  60487. enumerable: true,
  60488. configurable: true
  60489. });
  60490. StandardRenderingPipeline.prototype._buildPipeline = function () {
  60491. var _this = this;
  60492. var ratio = this._ratio;
  60493. var scene = this._scene;
  60494. this._disposePostProcesses();
  60495. this._reset();
  60496. // Create pass post-process
  60497. if (!this._basePostProcess) {
  60498. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  60499. this.originalPostProcess.onApply = function (effect) {
  60500. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  60501. };
  60502. }
  60503. else {
  60504. this.originalPostProcess = this._basePostProcess;
  60505. }
  60506. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  60507. this._currentDepthOfFieldSource = this.originalPostProcess;
  60508. if (this._vlsEnabled) {
  60509. // Create volumetric light
  60510. this._createVolumetricLightPostProcess(scene, ratio);
  60511. // Create volumetric light final post-process
  60512. 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);
  60513. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  60514. }
  60515. if (this._bloomEnabled) {
  60516. // Create down sample X4 post-process
  60517. this._createDownSampleX4PostProcess(scene, ratio / 2);
  60518. // Create bright pass post-process
  60519. this._createBrightPassPostProcess(scene, ratio / 2);
  60520. // Create gaussian blur post-processes (down sampling blurs)
  60521. this._createBlurPostProcesses(scene, ratio / 4, 1);
  60522. // Create texture adder post-process
  60523. this._createTextureAdderPostProcess(scene, ratio);
  60524. // Create depth-of-field source post-process
  60525. 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);
  60526. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  60527. }
  60528. if (this._lensFlareEnabled) {
  60529. // Create lens flare post-process
  60530. this._createLensFlarePostProcess(scene, ratio);
  60531. // Create depth-of-field source post-process post lens-flare and disable it now
  60532. 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);
  60533. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  60534. }
  60535. if (this._hdrEnabled) {
  60536. // Create luminance
  60537. this._createLuminancePostProcesses(scene, this._floatTextureType);
  60538. // Create HDR
  60539. this._createHdrPostProcess(scene, ratio);
  60540. // Create depth-of-field source post-process post hdr and disable it now
  60541. 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);
  60542. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  60543. }
  60544. if (this._depthOfFieldEnabled) {
  60545. // Create gaussian blur used by depth-of-field
  60546. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  60547. // Create depth-of-field post-process
  60548. this._createDepthOfFieldPostProcess(scene, ratio);
  60549. }
  60550. if (this._motionBlurEnabled) {
  60551. // Create motion blur post-process
  60552. this._createMotionBlurPostProcess(scene, ratio);
  60553. }
  60554. if (this._cameras !== null) {
  60555. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  60556. }
  60557. };
  60558. // Down Sample X4 Post-Processs
  60559. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  60560. var _this = this;
  60561. var downSampleX4Offsets = new Array(32);
  60562. 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);
  60563. this.downSampleX4PostProcess.onApply = function (effect) {
  60564. var id = 0;
  60565. var width = _this.downSampleX4PostProcess.width;
  60566. var height = _this.downSampleX4PostProcess.height;
  60567. for (var i = -2; i < 2; i++) {
  60568. for (var j = -2; j < 2; j++) {
  60569. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  60570. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  60571. id += 2;
  60572. }
  60573. }
  60574. effect.setArray2("dsOffsets", downSampleX4Offsets);
  60575. };
  60576. // Add to pipeline
  60577. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  60578. };
  60579. // Brightpass Post-Process
  60580. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  60581. var _this = this;
  60582. var brightOffsets = new Array(8);
  60583. 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);
  60584. this.brightPassPostProcess.onApply = function (effect) {
  60585. var sU = (1.0 / _this.brightPassPostProcess.width);
  60586. var sV = (1.0 / _this.brightPassPostProcess.height);
  60587. brightOffsets[0] = -0.5 * sU;
  60588. brightOffsets[1] = 0.5 * sV;
  60589. brightOffsets[2] = 0.5 * sU;
  60590. brightOffsets[3] = 0.5 * sV;
  60591. brightOffsets[4] = -0.5 * sU;
  60592. brightOffsets[5] = -0.5 * sV;
  60593. brightOffsets[6] = 0.5 * sU;
  60594. brightOffsets[7] = -0.5 * sV;
  60595. effect.setArray2("dsOffsets", brightOffsets);
  60596. effect.setFloat("brightThreshold", _this.brightThreshold);
  60597. };
  60598. // Add to pipeline
  60599. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  60600. };
  60601. // Create blur H&V post-processes
  60602. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  60603. var _this = this;
  60604. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  60605. var engine = scene.getEngine();
  60606. 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);
  60607. 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);
  60608. blurX.onActivateObservable.add(function () {
  60609. var dw = blurX.width / engine.getRenderWidth();
  60610. blurX.kernel = _this[blurWidthKey] * dw;
  60611. });
  60612. blurY.onActivateObservable.add(function () {
  60613. var dw = blurY.height / engine.getRenderHeight();
  60614. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  60615. });
  60616. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  60617. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  60618. this.blurHPostProcesses.push(blurX);
  60619. this.blurVPostProcesses.push(blurY);
  60620. };
  60621. // Create texture adder post-process
  60622. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  60623. var _this = this;
  60624. 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);
  60625. this.textureAdderPostProcess.onApply = function (effect) {
  60626. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  60627. effect.setTexture("lensSampler", _this.lensTexture);
  60628. effect.setFloat("exposure", _this.exposure);
  60629. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  60630. };
  60631. // Add to pipeline
  60632. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  60633. };
  60634. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  60635. var _this = this;
  60636. var geometryRenderer = scene.enableGeometryBufferRenderer();
  60637. geometryRenderer.enablePosition = true;
  60638. var geometry = geometryRenderer.getGBuffer();
  60639. // Base post-process
  60640. 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));
  60641. var depthValues = BABYLON.Vector2.Zero();
  60642. this.volumetricLightPostProcess.onApply = function (effect) {
  60643. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  60644. var generator = _this.sourceLight.getShadowGenerator();
  60645. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  60646. effect.setTexture("positionSampler", geometry.textures[2]);
  60647. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  60648. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  60649. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  60650. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  60651. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  60652. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  60653. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  60654. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  60655. effect.setVector2("depthValues", depthValues);
  60656. }
  60657. };
  60658. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  60659. // Smooth
  60660. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  60661. // Merge
  60662. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  60663. this.volumetricLightMergePostProces.onApply = function (effect) {
  60664. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  60665. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  60666. };
  60667. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  60668. };
  60669. // Create luminance
  60670. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  60671. var _this = this;
  60672. // Create luminance
  60673. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  60674. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  60675. var offsets = [];
  60676. this.luminancePostProcess.onApply = function (effect) {
  60677. var sU = (1.0 / _this.luminancePostProcess.width);
  60678. var sV = (1.0 / _this.luminancePostProcess.height);
  60679. offsets[0] = -0.5 * sU;
  60680. offsets[1] = 0.5 * sV;
  60681. offsets[2] = 0.5 * sU;
  60682. offsets[3] = 0.5 * sV;
  60683. offsets[4] = -0.5 * sU;
  60684. offsets[5] = -0.5 * sV;
  60685. offsets[6] = 0.5 * sU;
  60686. offsets[7] = -0.5 * sV;
  60687. effect.setArray2("lumOffsets", offsets);
  60688. };
  60689. // Add to pipeline
  60690. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  60691. // Create down sample luminance
  60692. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  60693. var size = Math.pow(3, i);
  60694. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  60695. if (i === 0) {
  60696. defines += "#define FINAL_DOWN_SAMPLER";
  60697. }
  60698. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  60699. this.luminanceDownSamplePostProcesses.push(postProcess);
  60700. }
  60701. // Create callbacks and add effects
  60702. var lastLuminance = this.luminancePostProcess;
  60703. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  60704. var downSampleOffsets = new Array(18);
  60705. pp.onApply = function (effect) {
  60706. if (!lastLuminance) {
  60707. return;
  60708. }
  60709. var id = 0;
  60710. for (var x = -1; x < 2; x++) {
  60711. for (var y = -1; y < 2; y++) {
  60712. downSampleOffsets[id] = x / lastLuminance.width;
  60713. downSampleOffsets[id + 1] = y / lastLuminance.height;
  60714. id += 2;
  60715. }
  60716. }
  60717. effect.setArray2("dsOffsets", downSampleOffsets);
  60718. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  60719. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  60720. lastLuminance = _this.luminancePostProcess;
  60721. }
  60722. else {
  60723. lastLuminance = pp;
  60724. }
  60725. };
  60726. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  60727. pp.onAfterRender = function (effect) {
  60728. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  60729. 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);
  60730. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  60731. };
  60732. }
  60733. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  60734. });
  60735. };
  60736. // Create HDR post-process
  60737. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  60738. var _this = this;
  60739. 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);
  60740. var outputLiminance = 1;
  60741. var time = 0;
  60742. var lastTime = 0;
  60743. this.hdrPostProcess.onApply = function (effect) {
  60744. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  60745. time += scene.getEngine().getDeltaTime();
  60746. if (outputLiminance < 0) {
  60747. outputLiminance = _this._hdrCurrentLuminance;
  60748. }
  60749. else {
  60750. var dt = (lastTime - time) / 1000.0;
  60751. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  60752. outputLiminance += _this.hdrDecreaseRate * dt;
  60753. }
  60754. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  60755. outputLiminance -= _this.hdrIncreaseRate * dt;
  60756. }
  60757. else {
  60758. outputLiminance = _this._hdrCurrentLuminance;
  60759. }
  60760. }
  60761. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  60762. effect.setFloat("averageLuminance", outputLiminance);
  60763. lastTime = time;
  60764. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  60765. };
  60766. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  60767. };
  60768. // Create lens flare post-process
  60769. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  60770. var _this = this;
  60771. 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);
  60772. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  60773. this._createBlurPostProcesses(scene, ratio / 4, 2);
  60774. 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);
  60775. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  60776. var resolution = new BABYLON.Vector2(0, 0);
  60777. // Lens flare
  60778. this.lensFlarePostProcess.onApply = function (effect) {
  60779. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  60780. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  60781. effect.setFloat("strength", _this.lensFlareStrength);
  60782. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  60783. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  60784. // Shift
  60785. resolution.x = _this.lensFlarePostProcess.width;
  60786. resolution.y = _this.lensFlarePostProcess.height;
  60787. effect.setVector2("resolution", resolution);
  60788. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  60789. };
  60790. // Compose
  60791. 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);
  60792. 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);
  60793. this.lensFlareComposePostProcess.onApply = function (effect) {
  60794. if (!_this._scene.activeCamera) {
  60795. return;
  60796. }
  60797. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  60798. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  60799. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  60800. // Lens start rotation matrix
  60801. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  60802. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  60803. 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));
  60804. camRot *= 4.0;
  60805. 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);
  60806. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  60807. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  60808. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  60809. };
  60810. };
  60811. // Create depth-of-field post-process
  60812. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  60813. var _this = this;
  60814. 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);
  60815. this.depthOfFieldPostProcess.onApply = function (effect) {
  60816. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  60817. effect.setTexture("depthSampler", _this._getDepthTexture());
  60818. effect.setFloat("distance", _this.depthOfFieldDistance);
  60819. };
  60820. // Add to pipeline
  60821. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  60822. };
  60823. // Create motion blur post-process
  60824. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  60825. var _this = this;
  60826. 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);
  60827. var motionScale = 0;
  60828. var prevViewProjection = BABYLON.Matrix.Identity();
  60829. var invViewProjection = BABYLON.Matrix.Identity();
  60830. var viewProjection = BABYLON.Matrix.Identity();
  60831. var screenSize = BABYLON.Vector2.Zero();
  60832. this.motionBlurPostProcess.onApply = function (effect) {
  60833. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  60834. viewProjection.invertToRef(invViewProjection);
  60835. effect.setMatrix("inverseViewProjection", invViewProjection);
  60836. effect.setMatrix("prevViewProjection", prevViewProjection);
  60837. prevViewProjection = viewProjection;
  60838. screenSize.x = _this.motionBlurPostProcess.width;
  60839. screenSize.y = _this.motionBlurPostProcess.height;
  60840. effect.setVector2("screenSize", screenSize);
  60841. motionScale = scene.getEngine().getFps() / 60.0;
  60842. effect.setFloat("motionScale", motionScale);
  60843. effect.setFloat("motionStrength", _this.motionStrength);
  60844. effect.setTexture("depthSampler", _this._getDepthTexture());
  60845. };
  60846. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  60847. };
  60848. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  60849. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  60850. var renderer = this._scene.enableGeometryBufferRenderer();
  60851. return renderer.getGBuffer().textures[0];
  60852. }
  60853. return this._scene.enableDepthRenderer().getDepthMap();
  60854. };
  60855. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  60856. for (var i = 0; i < this._cameras.length; i++) {
  60857. var camera = this._cameras[i];
  60858. if (this.originalPostProcess) {
  60859. this.originalPostProcess.dispose(camera);
  60860. }
  60861. if (this.downSampleX4PostProcess) {
  60862. this.downSampleX4PostProcess.dispose(camera);
  60863. }
  60864. if (this.brightPassPostProcess) {
  60865. this.brightPassPostProcess.dispose(camera);
  60866. }
  60867. if (this.textureAdderPostProcess) {
  60868. this.textureAdderPostProcess.dispose(camera);
  60869. }
  60870. if (this.textureAdderFinalPostProcess) {
  60871. this.textureAdderFinalPostProcess.dispose(camera);
  60872. }
  60873. if (this.volumetricLightPostProcess) {
  60874. this.volumetricLightPostProcess.dispose(camera);
  60875. }
  60876. if (this.volumetricLightSmoothXPostProcess) {
  60877. this.volumetricLightSmoothXPostProcess.dispose(camera);
  60878. }
  60879. if (this.volumetricLightSmoothYPostProcess) {
  60880. this.volumetricLightSmoothYPostProcess.dispose(camera);
  60881. }
  60882. if (this.volumetricLightMergePostProces) {
  60883. this.volumetricLightMergePostProces.dispose(camera);
  60884. }
  60885. if (this.volumetricLightFinalPostProcess) {
  60886. this.volumetricLightFinalPostProcess.dispose(camera);
  60887. }
  60888. if (this.lensFlarePostProcess) {
  60889. this.lensFlarePostProcess.dispose(camera);
  60890. }
  60891. if (this.lensFlareComposePostProcess) {
  60892. this.lensFlareComposePostProcess.dispose(camera);
  60893. }
  60894. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  60895. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  60896. }
  60897. if (this.luminancePostProcess) {
  60898. this.luminancePostProcess.dispose(camera);
  60899. }
  60900. if (this.hdrPostProcess) {
  60901. this.hdrPostProcess.dispose(camera);
  60902. }
  60903. if (this.hdrFinalPostProcess) {
  60904. this.hdrFinalPostProcess.dispose(camera);
  60905. }
  60906. if (this.depthOfFieldPostProcess) {
  60907. this.depthOfFieldPostProcess.dispose(camera);
  60908. }
  60909. if (this.motionBlurPostProcess) {
  60910. this.motionBlurPostProcess.dispose(camera);
  60911. }
  60912. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  60913. this.blurHPostProcesses[j].dispose(camera);
  60914. }
  60915. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  60916. this.blurVPostProcesses[j].dispose(camera);
  60917. }
  60918. }
  60919. this.originalPostProcess = null;
  60920. this.downSampleX4PostProcess = null;
  60921. this.brightPassPostProcess = null;
  60922. this.textureAdderPostProcess = null;
  60923. this.textureAdderFinalPostProcess = null;
  60924. this.volumetricLightPostProcess = null;
  60925. this.volumetricLightSmoothXPostProcess = null;
  60926. this.volumetricLightSmoothYPostProcess = null;
  60927. this.volumetricLightMergePostProces = null;
  60928. this.volumetricLightFinalPostProcess = null;
  60929. this.lensFlarePostProcess = null;
  60930. this.lensFlareComposePostProcess = null;
  60931. this.luminancePostProcess = null;
  60932. this.hdrPostProcess = null;
  60933. this.hdrFinalPostProcess = null;
  60934. this.depthOfFieldPostProcess = null;
  60935. this.motionBlurPostProcess = null;
  60936. this.luminanceDownSamplePostProcesses = [];
  60937. this.blurHPostProcesses = [];
  60938. this.blurVPostProcesses = [];
  60939. };
  60940. // Dispose
  60941. StandardRenderingPipeline.prototype.dispose = function () {
  60942. this._disposePostProcesses();
  60943. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  60944. _super.prototype.dispose.call(this);
  60945. };
  60946. // Serialize rendering pipeline
  60947. StandardRenderingPipeline.prototype.serialize = function () {
  60948. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  60949. serializationObject.customType = "StandardRenderingPipeline";
  60950. return serializationObject;
  60951. };
  60952. /**
  60953. * Static members
  60954. */
  60955. // Parse serialized pipeline
  60956. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  60957. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  60958. };
  60959. // Luminance steps
  60960. StandardRenderingPipeline.LuminanceSteps = 6;
  60961. __decorate([
  60962. BABYLON.serialize()
  60963. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  60964. __decorate([
  60965. BABYLON.serialize()
  60966. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  60967. __decorate([
  60968. BABYLON.serialize()
  60969. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  60970. __decorate([
  60971. BABYLON.serialize()
  60972. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  60973. __decorate([
  60974. BABYLON.serializeAsTexture("lensTexture")
  60975. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  60976. __decorate([
  60977. BABYLON.serialize()
  60978. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  60979. __decorate([
  60980. BABYLON.serialize()
  60981. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  60982. __decorate([
  60983. BABYLON.serialize()
  60984. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  60985. __decorate([
  60986. BABYLON.serialize()
  60987. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  60988. __decorate([
  60989. BABYLON.serialize()
  60990. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  60991. __decorate([
  60992. BABYLON.serialize()
  60993. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  60994. __decorate([
  60995. BABYLON.serializeAsTexture("lensColorTexture")
  60996. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  60997. __decorate([
  60998. BABYLON.serialize()
  60999. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  61000. __decorate([
  61001. BABYLON.serialize()
  61002. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  61003. __decorate([
  61004. BABYLON.serialize()
  61005. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  61006. __decorate([
  61007. BABYLON.serialize()
  61008. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  61009. __decorate([
  61010. BABYLON.serializeAsTexture("lensStarTexture")
  61011. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  61012. __decorate([
  61013. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  61014. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  61015. __decorate([
  61016. BABYLON.serialize()
  61017. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  61018. __decorate([
  61019. BABYLON.serialize()
  61020. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  61021. __decorate([
  61022. BABYLON.serialize()
  61023. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  61024. __decorate([
  61025. BABYLON.serialize()
  61026. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  61027. __decorate([
  61028. BABYLON.serialize()
  61029. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  61030. __decorate([
  61031. BABYLON.serialize()
  61032. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  61033. __decorate([
  61034. BABYLON.serialize()
  61035. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  61036. __decorate([
  61037. BABYLON.serialize()
  61038. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  61039. __decorate([
  61040. BABYLON.serialize()
  61041. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  61042. __decorate([
  61043. BABYLON.serialize()
  61044. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  61045. __decorate([
  61046. BABYLON.serialize()
  61047. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  61048. __decorate([
  61049. BABYLON.serialize()
  61050. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  61051. return StandardRenderingPipeline;
  61052. }(BABYLON.PostProcessRenderPipeline));
  61053. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  61054. })(BABYLON || (BABYLON = {}));
  61055. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  61056. var BABYLON;
  61057. (function (BABYLON) {
  61058. var FxaaPostProcess = /** @class */ (function (_super) {
  61059. __extends(FxaaPostProcess, _super);
  61060. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  61061. if (camera === void 0) { camera = null; }
  61062. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61063. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  61064. _this.onApplyObservable.add(function (effect) {
  61065. var texelSize = _this.texelSize;
  61066. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  61067. });
  61068. return _this;
  61069. }
  61070. return FxaaPostProcess;
  61071. }(BABYLON.PostProcess));
  61072. BABYLON.FxaaPostProcess = FxaaPostProcess;
  61073. })(BABYLON || (BABYLON = {}));
  61074. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  61075. var BABYLON;
  61076. (function (BABYLON) {
  61077. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  61078. __extends(DefaultRenderingPipeline, _super);
  61079. /**
  61080. * @constructor
  61081. * @param {string} name - The rendering pipeline name
  61082. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  61083. * @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)
  61084. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  61085. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  61086. */
  61087. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  61088. if (automaticBuild === void 0) { automaticBuild = true; }
  61089. var _this = _super.call(this, scene.getEngine(), name) || this;
  61090. _this.PassPostProcessId = "PassPostProcessEffect";
  61091. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  61092. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  61093. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  61094. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  61095. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  61096. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  61097. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  61098. // IAnimatable
  61099. _this.animations = [];
  61100. // Values
  61101. _this._bloomEnabled = false;
  61102. _this._fxaaEnabled = false;
  61103. _this._imageProcessingEnabled = true;
  61104. _this._bloomScale = 0.6;
  61105. _this._buildAllowed = true;
  61106. /**
  61107. * Specifies the size of the bloom blur kernel, relative to the final output size
  61108. */
  61109. _this.bloomKernel = 64;
  61110. /**
  61111. * Specifies the weight of the bloom in the final rendering
  61112. */
  61113. _this._bloomWeight = 0.15;
  61114. _this._cameras = cameras || [];
  61115. _this._buildAllowed = automaticBuild;
  61116. // Initialize
  61117. _this._scene = scene;
  61118. var caps = _this._scene.getEngine().getCaps();
  61119. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  61120. // Misc
  61121. if (_this._hdr) {
  61122. if (caps.textureHalfFloatRender) {
  61123. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  61124. }
  61125. else if (caps.textureFloatRender) {
  61126. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  61127. }
  61128. }
  61129. else {
  61130. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  61131. }
  61132. // Attach
  61133. scene.postProcessRenderPipelineManager.addPipeline(_this);
  61134. _this._buildPipeline();
  61135. return _this;
  61136. }
  61137. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  61138. get: function () {
  61139. return this._bloomWeight;
  61140. },
  61141. set: function (value) {
  61142. if (this._bloomWeight === value) {
  61143. return;
  61144. }
  61145. this._bloomWeight = value;
  61146. if (this._hdr && this.copyBack) {
  61147. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  61148. }
  61149. },
  61150. enumerable: true,
  61151. configurable: true
  61152. });
  61153. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  61154. get: function () {
  61155. return this._bloomScale;
  61156. },
  61157. set: function (value) {
  61158. if (this._bloomScale === value) {
  61159. return;
  61160. }
  61161. this._bloomScale = value;
  61162. this._buildPipeline();
  61163. },
  61164. enumerable: true,
  61165. configurable: true
  61166. });
  61167. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  61168. get: function () {
  61169. return this._bloomEnabled;
  61170. },
  61171. set: function (enabled) {
  61172. if (this._bloomEnabled === enabled) {
  61173. return;
  61174. }
  61175. this._bloomEnabled = enabled;
  61176. this._buildPipeline();
  61177. },
  61178. enumerable: true,
  61179. configurable: true
  61180. });
  61181. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  61182. get: function () {
  61183. return this._fxaaEnabled;
  61184. },
  61185. set: function (enabled) {
  61186. if (this._fxaaEnabled === enabled) {
  61187. return;
  61188. }
  61189. this._fxaaEnabled = enabled;
  61190. this._buildPipeline();
  61191. },
  61192. enumerable: true,
  61193. configurable: true
  61194. });
  61195. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  61196. get: function () {
  61197. return this._imageProcessingEnabled;
  61198. },
  61199. set: function (enabled) {
  61200. if (this._imageProcessingEnabled === enabled) {
  61201. return;
  61202. }
  61203. this._imageProcessingEnabled = enabled;
  61204. this._buildPipeline();
  61205. },
  61206. enumerable: true,
  61207. configurable: true
  61208. });
  61209. /**
  61210. * Force the compilation of the entire pipeline.
  61211. */
  61212. DefaultRenderingPipeline.prototype.prepare = function () {
  61213. var previousState = this._buildAllowed;
  61214. this._buildAllowed = true;
  61215. this._buildPipeline();
  61216. this._buildAllowed = previousState;
  61217. };
  61218. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  61219. var _this = this;
  61220. if (!this._buildAllowed) {
  61221. return;
  61222. }
  61223. var engine = this._scene.getEngine();
  61224. this._disposePostProcesses();
  61225. this._reset();
  61226. if (this.bloomEnabled) {
  61227. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61228. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  61229. if (!this._hdr) {
  61230. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61231. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  61232. this.highlights.autoClear = false;
  61233. this.highlights.alwaysForcePOT = true;
  61234. }
  61235. 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);
  61236. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  61237. this.blurX.alwaysForcePOT = true;
  61238. this.blurX.autoClear = false;
  61239. this.blurX.onActivateObservable.add(function () {
  61240. var dw = _this.blurX.width / engine.getRenderWidth(true);
  61241. _this.blurX.kernel = _this.bloomKernel * dw;
  61242. });
  61243. 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);
  61244. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  61245. this.blurY.alwaysForcePOT = true;
  61246. this.blurY.autoClear = false;
  61247. this.blurY.onActivateObservable.add(function () {
  61248. var dh = _this.blurY.height / engine.getRenderHeight(true);
  61249. _this.blurY.kernel = _this.bloomKernel * dh;
  61250. });
  61251. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61252. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  61253. this.copyBack.alwaysForcePOT = true;
  61254. if (this._hdr) {
  61255. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  61256. var w = this.bloomWeight;
  61257. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  61258. }
  61259. else {
  61260. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  61261. }
  61262. this.copyBack.autoClear = false;
  61263. }
  61264. if (this._imageProcessingEnabled) {
  61265. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61266. if (this._hdr) {
  61267. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  61268. }
  61269. else {
  61270. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  61271. }
  61272. }
  61273. if (this.fxaaEnabled) {
  61274. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61275. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  61276. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  61277. }
  61278. else if (this._hdr && this.imageProcessing) {
  61279. this.finalMerge = this.imageProcessing;
  61280. }
  61281. else {
  61282. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61283. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  61284. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  61285. }
  61286. if (this.bloomEnabled) {
  61287. if (this._hdr) {
  61288. this.copyBack.shareOutputWith(this.blurX);
  61289. if (this.imageProcessing) {
  61290. this.imageProcessing.shareOutputWith(this.pass);
  61291. this.imageProcessing.autoClear = false;
  61292. }
  61293. else if (this.fxaa) {
  61294. this.fxaa.shareOutputWith(this.pass);
  61295. }
  61296. else {
  61297. this.finalMerge.shareOutputWith(this.pass);
  61298. }
  61299. }
  61300. else {
  61301. if (this.fxaa) {
  61302. this.fxaa.shareOutputWith(this.pass);
  61303. }
  61304. else {
  61305. this.finalMerge.shareOutputWith(this.pass);
  61306. }
  61307. }
  61308. }
  61309. if (this._cameras !== null) {
  61310. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  61311. }
  61312. };
  61313. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  61314. for (var i = 0; i < this._cameras.length; i++) {
  61315. var camera = this._cameras[i];
  61316. if (this.pass) {
  61317. this.pass.dispose(camera);
  61318. }
  61319. if (this.highlights) {
  61320. this.highlights.dispose(camera);
  61321. }
  61322. if (this.blurX) {
  61323. this.blurX.dispose(camera);
  61324. }
  61325. if (this.blurY) {
  61326. this.blurY.dispose(camera);
  61327. }
  61328. if (this.copyBack) {
  61329. this.copyBack.dispose(camera);
  61330. }
  61331. if (this.imageProcessing) {
  61332. this.imageProcessing.dispose(camera);
  61333. }
  61334. if (this.fxaa) {
  61335. this.fxaa.dispose(camera);
  61336. }
  61337. if (this.finalMerge) {
  61338. this.finalMerge.dispose(camera);
  61339. }
  61340. }
  61341. this.pass = null;
  61342. this.highlights = null;
  61343. this.blurX = null;
  61344. this.blurY = null;
  61345. this.copyBack = null;
  61346. this.imageProcessing = null;
  61347. this.fxaa = null;
  61348. this.finalMerge = null;
  61349. };
  61350. // Dispose
  61351. DefaultRenderingPipeline.prototype.dispose = function () {
  61352. this._disposePostProcesses();
  61353. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  61354. _super.prototype.dispose.call(this);
  61355. };
  61356. // Serialize rendering pipeline
  61357. DefaultRenderingPipeline.prototype.serialize = function () {
  61358. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  61359. serializationObject.customType = "DefaultRenderingPipeline";
  61360. return serializationObject;
  61361. };
  61362. // Parse serialized pipeline
  61363. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  61364. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  61365. };
  61366. __decorate([
  61367. BABYLON.serialize()
  61368. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  61369. __decorate([
  61370. BABYLON.serialize()
  61371. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  61372. __decorate([
  61373. BABYLON.serialize()
  61374. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  61375. __decorate([
  61376. BABYLON.serialize()
  61377. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  61378. __decorate([
  61379. BABYLON.serialize()
  61380. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  61381. __decorate([
  61382. BABYLON.serialize()
  61383. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  61384. __decorate([
  61385. BABYLON.serialize()
  61386. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  61387. __decorate([
  61388. BABYLON.serialize()
  61389. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  61390. return DefaultRenderingPipeline;
  61391. }(BABYLON.PostProcessRenderPipeline));
  61392. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  61393. })(BABYLON || (BABYLON = {}));
  61394. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  61395. var BABYLON;
  61396. (function (BABYLON) {
  61397. var GeometryBufferRenderer = /** @class */ (function () {
  61398. function GeometryBufferRenderer(scene, ratio) {
  61399. if (ratio === void 0) { ratio = 1; }
  61400. this._enablePosition = false;
  61401. this._scene = scene;
  61402. this._ratio = ratio;
  61403. // Render target
  61404. this._createRenderTargets();
  61405. }
  61406. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  61407. set: function (meshes) {
  61408. this._multiRenderTarget.renderList = meshes;
  61409. },
  61410. enumerable: true,
  61411. configurable: true
  61412. });
  61413. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  61414. get: function () {
  61415. return this._multiRenderTarget.isSupported;
  61416. },
  61417. enumerable: true,
  61418. configurable: true
  61419. });
  61420. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  61421. get: function () {
  61422. return this._enablePosition;
  61423. },
  61424. set: function (enable) {
  61425. this._enablePosition = enable;
  61426. this.dispose();
  61427. this._createRenderTargets();
  61428. },
  61429. enumerable: true,
  61430. configurable: true
  61431. });
  61432. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  61433. var material = subMesh.getMaterial();
  61434. if (material && material.disableDepthWrite) {
  61435. return false;
  61436. }
  61437. var defines = [];
  61438. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  61439. var mesh = subMesh.getMesh();
  61440. // Alpha test
  61441. if (material && material.needAlphaTesting()) {
  61442. defines.push("#define ALPHATEST");
  61443. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  61444. attribs.push(BABYLON.VertexBuffer.UVKind);
  61445. defines.push("#define UV1");
  61446. }
  61447. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  61448. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  61449. defines.push("#define UV2");
  61450. }
  61451. }
  61452. // Buffers
  61453. if (this._enablePosition) {
  61454. defines.push("#define POSITION");
  61455. }
  61456. // Bones
  61457. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61458. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  61459. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  61460. if (mesh.numBoneInfluencers > 4) {
  61461. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  61462. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  61463. }
  61464. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  61465. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  61466. }
  61467. else {
  61468. defines.push("#define NUM_BONE_INFLUENCERS 0");
  61469. }
  61470. // Instances
  61471. if (useInstances) {
  61472. defines.push("#define INSTANCES");
  61473. attribs.push("world0");
  61474. attribs.push("world1");
  61475. attribs.push("world2");
  61476. attribs.push("world3");
  61477. }
  61478. // Get correct effect
  61479. var join = defines.join("\n");
  61480. if (this._cachedDefines !== join) {
  61481. this._cachedDefines = join;
  61482. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  61483. }
  61484. return this._effect.isReady();
  61485. };
  61486. GeometryBufferRenderer.prototype.getGBuffer = function () {
  61487. return this._multiRenderTarget;
  61488. };
  61489. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  61490. get: function () {
  61491. return this._multiRenderTarget.samples;
  61492. },
  61493. set: function (value) {
  61494. this._multiRenderTarget.samples = value;
  61495. },
  61496. enumerable: true,
  61497. configurable: true
  61498. });
  61499. // Methods
  61500. GeometryBufferRenderer.prototype.dispose = function () {
  61501. this.getGBuffer().dispose();
  61502. };
  61503. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  61504. var _this = this;
  61505. var engine = this._scene.getEngine();
  61506. var count = this._enablePosition ? 3 : 2;
  61507. 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 });
  61508. if (!this.isSupported) {
  61509. return;
  61510. }
  61511. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61512. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61513. this._multiRenderTarget.refreshRate = 1;
  61514. this._multiRenderTarget.renderParticles = false;
  61515. this._multiRenderTarget.renderList = null;
  61516. // set default depth value to 1.0 (far away)
  61517. this._multiRenderTarget.onClearObservable.add(function (engine) {
  61518. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  61519. });
  61520. // Custom render function
  61521. var renderSubMesh = function (subMesh) {
  61522. var mesh = subMesh.getRenderingMesh();
  61523. var scene = _this._scene;
  61524. var engine = scene.getEngine();
  61525. var material = subMesh.getMaterial();
  61526. if (!material) {
  61527. return;
  61528. }
  61529. // Culling
  61530. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  61531. // Managing instances
  61532. var batch = mesh._getInstancesRenderList(subMesh._id);
  61533. if (batch.mustReturn) {
  61534. return;
  61535. }
  61536. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  61537. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  61538. engine.enableEffect(_this._effect);
  61539. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  61540. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  61541. _this._effect.setMatrix("view", scene.getViewMatrix());
  61542. // Alpha test
  61543. if (material && material.needAlphaTesting()) {
  61544. var alphaTexture = material.getAlphaTestTexture();
  61545. if (alphaTexture) {
  61546. _this._effect.setTexture("diffuseSampler", alphaTexture);
  61547. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  61548. }
  61549. }
  61550. // Bones
  61551. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  61552. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  61553. }
  61554. // Draw
  61555. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  61556. }
  61557. };
  61558. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  61559. var index;
  61560. if (depthOnlySubMeshes.length) {
  61561. engine.setColorWrite(false);
  61562. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  61563. renderSubMesh(depthOnlySubMeshes.data[index]);
  61564. }
  61565. engine.setColorWrite(true);
  61566. }
  61567. for (index = 0; index < opaqueSubMeshes.length; index++) {
  61568. renderSubMesh(opaqueSubMeshes.data[index]);
  61569. }
  61570. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  61571. renderSubMesh(alphaTestSubMeshes.data[index]);
  61572. }
  61573. };
  61574. };
  61575. return GeometryBufferRenderer;
  61576. }());
  61577. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  61578. })(BABYLON || (BABYLON = {}));
  61579. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  61580. var BABYLON;
  61581. (function (BABYLON) {
  61582. var RefractionPostProcess = /** @class */ (function (_super) {
  61583. __extends(RefractionPostProcess, _super);
  61584. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  61585. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  61586. _this.color = color;
  61587. _this.depth = depth;
  61588. _this.colorLevel = colorLevel;
  61589. _this.onActivateObservable.add(function (cam) {
  61590. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  61591. });
  61592. _this.onApplyObservable.add(function (effect) {
  61593. effect.setColor3("baseColor", _this.color);
  61594. effect.setFloat("depth", _this.depth);
  61595. effect.setFloat("colorLevel", _this.colorLevel);
  61596. effect.setTexture("refractionSampler", _this._refRexture);
  61597. });
  61598. return _this;
  61599. }
  61600. // Methods
  61601. RefractionPostProcess.prototype.dispose = function (camera) {
  61602. if (this._refRexture) {
  61603. this._refRexture.dispose();
  61604. }
  61605. _super.prototype.dispose.call(this, camera);
  61606. };
  61607. return RefractionPostProcess;
  61608. }(BABYLON.PostProcess));
  61609. BABYLON.RefractionPostProcess = RefractionPostProcess;
  61610. })(BABYLON || (BABYLON = {}));
  61611. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  61612. var BABYLON;
  61613. (function (BABYLON) {
  61614. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  61615. __extends(BlackAndWhitePostProcess, _super);
  61616. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  61617. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  61618. _this.degree = 1;
  61619. _this.onApplyObservable.add(function (effect) {
  61620. effect.setFloat("degree", _this.degree);
  61621. });
  61622. return _this;
  61623. }
  61624. return BlackAndWhitePostProcess;
  61625. }(BABYLON.PostProcess));
  61626. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  61627. })(BABYLON || (BABYLON = {}));
  61628. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  61629. var BABYLON;
  61630. (function (BABYLON) {
  61631. var ConvolutionPostProcess = /** @class */ (function (_super) {
  61632. __extends(ConvolutionPostProcess, _super);
  61633. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  61634. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  61635. _this.kernel = kernel;
  61636. _this.onApply = function (effect) {
  61637. effect.setFloat2("screenSize", _this.width, _this.height);
  61638. effect.setArray("kernel", _this.kernel);
  61639. };
  61640. return _this;
  61641. }
  61642. // Statics
  61643. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  61644. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  61645. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  61646. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  61647. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  61648. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  61649. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  61650. return ConvolutionPostProcess;
  61651. }(BABYLON.PostProcess));
  61652. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  61653. })(BABYLON || (BABYLON = {}));
  61654. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  61655. var BABYLON;
  61656. (function (BABYLON) {
  61657. var FilterPostProcess = /** @class */ (function (_super) {
  61658. __extends(FilterPostProcess, _super);
  61659. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  61660. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  61661. _this.kernelMatrix = kernelMatrix;
  61662. _this.onApply = function (effect) {
  61663. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  61664. };
  61665. return _this;
  61666. }
  61667. return FilterPostProcess;
  61668. }(BABYLON.PostProcess));
  61669. BABYLON.FilterPostProcess = FilterPostProcess;
  61670. })(BABYLON || (BABYLON = {}));
  61671. //# sourceMappingURL=babylon.filterPostProcess.js.map
  61672. var BABYLON;
  61673. (function (BABYLON) {
  61674. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  61675. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  61676. __extends(VolumetricLightScatteringPostProcess, _super);
  61677. /**
  61678. * @constructor
  61679. * @param {string} name - The post-process name
  61680. * @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)
  61681. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  61682. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  61683. * @param {number} samples - The post-process quality, default 100
  61684. * @param {number} samplingMode - The post-process filtering mode
  61685. * @param {BABYLON.Engine} engine - The babylon engine
  61686. * @param {boolean} reusable - If the post-process is reusable
  61687. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  61688. */
  61689. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  61690. if (samples === void 0) { samples = 100; }
  61691. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  61692. 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;
  61693. _this._screenCoordinates = BABYLON.Vector2.Zero();
  61694. /**
  61695. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  61696. * @type {Vector3}
  61697. */
  61698. _this.customMeshPosition = BABYLON.Vector3.Zero();
  61699. /**
  61700. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  61701. * @type {boolean}
  61702. */
  61703. _this.useCustomMeshPosition = false;
  61704. /**
  61705. * If the post-process should inverse the light scattering direction
  61706. * @type {boolean}
  61707. */
  61708. _this.invert = true;
  61709. /**
  61710. * Array containing the excluded meshes not rendered in the internal pass
  61711. */
  61712. _this.excludedMeshes = new Array();
  61713. /**
  61714. * Controls the overall intensity of the post-process
  61715. * @type {number}
  61716. */
  61717. _this.exposure = 0.3;
  61718. /**
  61719. * Dissipates each sample's contribution in range [0, 1]
  61720. * @type {number}
  61721. */
  61722. _this.decay = 0.96815;
  61723. /**
  61724. * Controls the overall intensity of each sample
  61725. * @type {number}
  61726. */
  61727. _this.weight = 0.58767;
  61728. /**
  61729. * Controls the density of each sample
  61730. * @type {number}
  61731. */
  61732. _this.density = 0.926;
  61733. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  61734. engine = scene.getEngine();
  61735. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  61736. // Configure mesh
  61737. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  61738. // Configure
  61739. _this._createPass(scene, ratio.passRatio || ratio);
  61740. _this.onActivate = function (camera) {
  61741. if (!_this.isSupported) {
  61742. _this.dispose(camera);
  61743. }
  61744. _this.onActivate = null;
  61745. };
  61746. _this.onApplyObservable.add(function (effect) {
  61747. _this._updateMeshScreenCoordinates(scene);
  61748. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  61749. effect.setFloat("exposure", _this.exposure);
  61750. effect.setFloat("decay", _this.decay);
  61751. effect.setFloat("weight", _this.weight);
  61752. effect.setFloat("density", _this.density);
  61753. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  61754. });
  61755. return _this;
  61756. }
  61757. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  61758. get: function () {
  61759. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  61760. return false;
  61761. },
  61762. set: function (useDiffuseColor) {
  61763. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  61764. },
  61765. enumerable: true,
  61766. configurable: true
  61767. });
  61768. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  61769. return "VolumetricLightScatteringPostProcess";
  61770. };
  61771. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  61772. var mesh = subMesh.getMesh();
  61773. // Render this.mesh as default
  61774. if (mesh === this.mesh && mesh.material) {
  61775. return mesh.material.isReady(mesh);
  61776. }
  61777. var defines = [];
  61778. var attribs = [BABYLON.VertexBuffer.PositionKind];
  61779. var material = subMesh.getMaterial();
  61780. // Alpha test
  61781. if (material) {
  61782. if (material.needAlphaTesting()) {
  61783. defines.push("#define ALPHATEST");
  61784. }
  61785. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  61786. attribs.push(BABYLON.VertexBuffer.UVKind);
  61787. defines.push("#define UV1");
  61788. }
  61789. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  61790. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  61791. defines.push("#define UV2");
  61792. }
  61793. }
  61794. // Bones
  61795. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61796. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  61797. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  61798. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  61799. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  61800. }
  61801. else {
  61802. defines.push("#define NUM_BONE_INFLUENCERS 0");
  61803. }
  61804. // Instances
  61805. if (useInstances) {
  61806. defines.push("#define INSTANCES");
  61807. attribs.push("world0");
  61808. attribs.push("world1");
  61809. attribs.push("world2");
  61810. attribs.push("world3");
  61811. }
  61812. // Get correct effect
  61813. var join = defines.join("\n");
  61814. if (this._cachedDefines !== join) {
  61815. this._cachedDefines = join;
  61816. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  61817. }
  61818. return this._volumetricLightScatteringPass.isReady();
  61819. };
  61820. /**
  61821. * Sets the new light position for light scattering effect
  61822. * @param {BABYLON.Vector3} The new custom light position
  61823. */
  61824. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  61825. this.customMeshPosition = position;
  61826. };
  61827. /**
  61828. * Returns the light position for light scattering effect
  61829. * @return {BABYLON.Vector3} The custom light position
  61830. */
  61831. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  61832. return this.customMeshPosition;
  61833. };
  61834. /**
  61835. * Disposes the internal assets and detaches the post-process from the camera
  61836. */
  61837. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  61838. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  61839. if (rttIndex !== -1) {
  61840. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  61841. }
  61842. this._volumetricLightScatteringRTT.dispose();
  61843. _super.prototype.dispose.call(this, camera);
  61844. };
  61845. /**
  61846. * Returns the render target texture used by the post-process
  61847. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  61848. */
  61849. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  61850. return this._volumetricLightScatteringRTT;
  61851. };
  61852. // Private methods
  61853. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  61854. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  61855. return true;
  61856. }
  61857. return false;
  61858. };
  61859. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  61860. var _this = this;
  61861. var engine = scene.getEngine();
  61862. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  61863. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61864. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61865. this._volumetricLightScatteringRTT.renderList = null;
  61866. this._volumetricLightScatteringRTT.renderParticles = false;
  61867. var camera = this.getCamera();
  61868. if (camera) {
  61869. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  61870. }
  61871. else {
  61872. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  61873. }
  61874. // Custom render function for submeshes
  61875. var renderSubMesh = function (subMesh) {
  61876. var mesh = subMesh.getRenderingMesh();
  61877. if (_this._meshExcluded(mesh)) {
  61878. return;
  61879. }
  61880. var material = subMesh.getMaterial();
  61881. if (!material) {
  61882. return;
  61883. }
  61884. var scene = mesh.getScene();
  61885. var engine = scene.getEngine();
  61886. // Culling
  61887. engine.setState(material.backFaceCulling);
  61888. // Managing instances
  61889. var batch = mesh._getInstancesRenderList(subMesh._id);
  61890. if (batch.mustReturn) {
  61891. return;
  61892. }
  61893. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  61894. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  61895. var effect = _this._volumetricLightScatteringPass;
  61896. if (mesh === _this.mesh) {
  61897. if (subMesh.effect) {
  61898. effect = subMesh.effect;
  61899. }
  61900. else {
  61901. effect = material.getEffect();
  61902. }
  61903. }
  61904. engine.enableEffect(effect);
  61905. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  61906. if (mesh === _this.mesh) {
  61907. material.bind(mesh.getWorldMatrix(), mesh);
  61908. }
  61909. else {
  61910. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  61911. // Alpha test
  61912. if (material && material.needAlphaTesting()) {
  61913. var alphaTexture = material.getAlphaTestTexture();
  61914. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  61915. if (alphaTexture) {
  61916. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  61917. }
  61918. }
  61919. // Bones
  61920. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  61921. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  61922. }
  61923. }
  61924. // Draw
  61925. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  61926. }
  61927. };
  61928. // Render target texture callbacks
  61929. var savedSceneClearColor;
  61930. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  61931. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  61932. savedSceneClearColor = scene.clearColor;
  61933. scene.clearColor = sceneClearColor;
  61934. });
  61935. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  61936. scene.clearColor = savedSceneClearColor;
  61937. });
  61938. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  61939. var engine = scene.getEngine();
  61940. var index;
  61941. if (depthOnlySubMeshes.length) {
  61942. engine.setColorWrite(false);
  61943. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  61944. renderSubMesh(depthOnlySubMeshes.data[index]);
  61945. }
  61946. engine.setColorWrite(true);
  61947. }
  61948. for (index = 0; index < opaqueSubMeshes.length; index++) {
  61949. renderSubMesh(opaqueSubMeshes.data[index]);
  61950. }
  61951. engine.setAlphaTesting(true);
  61952. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  61953. renderSubMesh(alphaTestSubMeshes.data[index]);
  61954. }
  61955. engine.setAlphaTesting(false);
  61956. if (transparentSubMeshes.length) {
  61957. // Sort sub meshes
  61958. for (index = 0; index < transparentSubMeshes.length; index++) {
  61959. var submesh = transparentSubMeshes.data[index];
  61960. var boundingInfo = submesh.getBoundingInfo();
  61961. if (boundingInfo && scene.activeCamera) {
  61962. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  61963. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  61964. }
  61965. }
  61966. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  61967. sortedArray.sort(function (a, b) {
  61968. // Alpha index first
  61969. if (a._alphaIndex > b._alphaIndex) {
  61970. return 1;
  61971. }
  61972. if (a._alphaIndex < b._alphaIndex) {
  61973. return -1;
  61974. }
  61975. // Then distance to camera
  61976. if (a._distanceToCamera < b._distanceToCamera) {
  61977. return 1;
  61978. }
  61979. if (a._distanceToCamera > b._distanceToCamera) {
  61980. return -1;
  61981. }
  61982. return 0;
  61983. });
  61984. // Render sub meshes
  61985. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  61986. for (index = 0; index < sortedArray.length; index++) {
  61987. renderSubMesh(sortedArray[index]);
  61988. }
  61989. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  61990. }
  61991. };
  61992. };
  61993. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  61994. var transform = scene.getTransformMatrix();
  61995. var meshPosition;
  61996. if (this.useCustomMeshPosition) {
  61997. meshPosition = this.customMeshPosition;
  61998. }
  61999. else if (this.attachedNode) {
  62000. meshPosition = this.attachedNode.position;
  62001. }
  62002. else {
  62003. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  62004. }
  62005. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  62006. this._screenCoordinates.x = pos.x / this._viewPort.width;
  62007. this._screenCoordinates.y = pos.y / this._viewPort.height;
  62008. if (this.invert)
  62009. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  62010. };
  62011. // Static methods
  62012. /**
  62013. * Creates a default mesh for the Volumeric Light Scattering post-process
  62014. * @param {string} The mesh name
  62015. * @param {BABYLON.Scene} The scene where to create the mesh
  62016. * @return {BABYLON.Mesh} the default mesh
  62017. */
  62018. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  62019. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  62020. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  62021. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  62022. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  62023. mesh.material = material;
  62024. return mesh;
  62025. };
  62026. __decorate([
  62027. BABYLON.serializeAsVector3()
  62028. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  62029. __decorate([
  62030. BABYLON.serialize()
  62031. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  62032. __decorate([
  62033. BABYLON.serialize()
  62034. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  62035. __decorate([
  62036. BABYLON.serializeAsMeshReference()
  62037. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  62038. __decorate([
  62039. BABYLON.serialize()
  62040. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  62041. __decorate([
  62042. BABYLON.serialize()
  62043. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  62044. __decorate([
  62045. BABYLON.serialize()
  62046. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  62047. __decorate([
  62048. BABYLON.serialize()
  62049. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  62050. __decorate([
  62051. BABYLON.serialize()
  62052. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  62053. return VolumetricLightScatteringPostProcess;
  62054. }(BABYLON.PostProcess));
  62055. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  62056. })(BABYLON || (BABYLON = {}));
  62057. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  62058. //
  62059. // This post-process allows the modification of rendered colors by using
  62060. // a 'look-up table' (LUT). This effect is also called Color Grading.
  62061. //
  62062. // The object needs to be provided an url to a texture containing the color
  62063. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  62064. // Use an image editing software to tweak the LUT to match your needs.
  62065. //
  62066. // For an example of a color LUT, see here:
  62067. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  62068. // For explanations on color grading, see here:
  62069. // http://udn.epicgames.com/Three/ColorGrading.html
  62070. //
  62071. var BABYLON;
  62072. (function (BABYLON) {
  62073. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  62074. __extends(ColorCorrectionPostProcess, _super);
  62075. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  62076. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  62077. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  62078. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  62079. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62080. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62081. _this.onApply = function (effect) {
  62082. effect.setTexture("colorTable", _this._colorTableTexture);
  62083. };
  62084. return _this;
  62085. }
  62086. return ColorCorrectionPostProcess;
  62087. }(BABYLON.PostProcess));
  62088. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  62089. })(BABYLON || (BABYLON = {}));
  62090. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  62091. var BABYLON;
  62092. (function (BABYLON) {
  62093. var TonemappingOperator;
  62094. (function (TonemappingOperator) {
  62095. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  62096. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  62097. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  62098. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  62099. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  62100. ;
  62101. var TonemapPostProcess = /** @class */ (function (_super) {
  62102. __extends(TonemapPostProcess, _super);
  62103. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  62104. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  62105. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62106. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  62107. _this._operator = _operator;
  62108. _this.exposureAdjustment = exposureAdjustment;
  62109. var defines = "#define ";
  62110. if (_this._operator === TonemappingOperator.Hable)
  62111. defines += "HABLE_TONEMAPPING";
  62112. else if (_this._operator === TonemappingOperator.Reinhard)
  62113. defines += "REINHARD_TONEMAPPING";
  62114. else if (_this._operator === TonemappingOperator.HejiDawson)
  62115. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  62116. else if (_this._operator === TonemappingOperator.Photographic)
  62117. defines += "PHOTOGRAPHIC_TONEMAPPING";
  62118. //sadly a second call to create the effect.
  62119. _this.updateEffect(defines);
  62120. _this.onApply = function (effect) {
  62121. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  62122. };
  62123. return _this;
  62124. }
  62125. return TonemapPostProcess;
  62126. }(BABYLON.PostProcess));
  62127. BABYLON.TonemapPostProcess = TonemapPostProcess;
  62128. })(BABYLON || (BABYLON = {}));
  62129. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  62130. var BABYLON;
  62131. (function (BABYLON) {
  62132. var DisplayPassPostProcess = /** @class */ (function (_super) {
  62133. __extends(DisplayPassPostProcess, _super);
  62134. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  62135. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  62136. }
  62137. return DisplayPassPostProcess;
  62138. }(BABYLON.PostProcess));
  62139. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  62140. })(BABYLON || (BABYLON = {}));
  62141. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  62142. var BABYLON;
  62143. (function (BABYLON) {
  62144. var HighlightsPostProcess = /** @class */ (function (_super) {
  62145. __extends(HighlightsPostProcess, _super);
  62146. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  62147. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62148. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  62149. }
  62150. return HighlightsPostProcess;
  62151. }(BABYLON.PostProcess));
  62152. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  62153. })(BABYLON || (BABYLON = {}));
  62154. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  62155. var BABYLON;
  62156. (function (BABYLON) {
  62157. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  62158. __extends(ImageProcessingPostProcess, _super);
  62159. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  62160. if (camera === void 0) { camera = null; }
  62161. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62162. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  62163. _this._fromLinearSpace = true;
  62164. /**
  62165. * Defines cache preventing GC.
  62166. */
  62167. _this._defines = {
  62168. IMAGEPROCESSING: false,
  62169. VIGNETTE: false,
  62170. VIGNETTEBLENDMODEMULTIPLY: false,
  62171. VIGNETTEBLENDMODEOPAQUE: false,
  62172. TONEMAPPING: false,
  62173. CONTRAST: false,
  62174. COLORCURVES: false,
  62175. COLORGRADING: false,
  62176. COLORGRADING3D: false,
  62177. FROMLINEARSPACE: false,
  62178. SAMPLER3DGREENDEPTH: false,
  62179. SAMPLER3DBGRMAP: false,
  62180. IMAGEPROCESSINGPOSTPROCESS: false,
  62181. EXPOSURE: false,
  62182. };
  62183. // Setup the configuration as forced by the constructor. This would then not force the
  62184. // scene materials output in linear space and let untouched the default forward pass.
  62185. if (imageProcessingConfiguration) {
  62186. imageProcessingConfiguration.applyByPostProcess = true;
  62187. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  62188. // This will cause the shader to be compiled
  62189. _this.fromLinearSpace = false;
  62190. }
  62191. else {
  62192. _this._attachImageProcessingConfiguration(null, true);
  62193. _this.imageProcessingConfiguration.applyByPostProcess = true;
  62194. }
  62195. _this.onApply = function (effect) {
  62196. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  62197. };
  62198. return _this;
  62199. }
  62200. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  62201. /**
  62202. * Gets the image processing configuration used either in this material.
  62203. */
  62204. get: function () {
  62205. return this._imageProcessingConfiguration;
  62206. },
  62207. /**
  62208. * Sets the Default image processing configuration used either in the this material.
  62209. *
  62210. * If sets to null, the scene one is in use.
  62211. */
  62212. set: function (value) {
  62213. this._attachImageProcessingConfiguration(value);
  62214. },
  62215. enumerable: true,
  62216. configurable: true
  62217. });
  62218. /**
  62219. * Attaches a new image processing configuration to the PBR Material.
  62220. * @param configuration
  62221. */
  62222. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  62223. var _this = this;
  62224. if (doNotBuild === void 0) { doNotBuild = false; }
  62225. if (configuration === this._imageProcessingConfiguration) {
  62226. return;
  62227. }
  62228. // Detaches observer.
  62229. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  62230. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  62231. }
  62232. // Pick the scene configuration if needed.
  62233. if (!configuration) {
  62234. var scene = null;
  62235. var engine = this.getEngine();
  62236. var camera = this.getCamera();
  62237. if (camera) {
  62238. scene = camera.getScene();
  62239. }
  62240. else if (engine && engine.scenes) {
  62241. var scenes = engine.scenes;
  62242. scene = scenes[scenes.length - 1];
  62243. }
  62244. else {
  62245. scene = BABYLON.Engine.LastCreatedScene;
  62246. }
  62247. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  62248. }
  62249. else {
  62250. this._imageProcessingConfiguration = configuration;
  62251. }
  62252. // Attaches observer.
  62253. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  62254. _this._updateParameters();
  62255. });
  62256. // Ensure the effect will be rebuilt.
  62257. if (!doNotBuild) {
  62258. this._updateParameters();
  62259. }
  62260. };
  62261. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  62262. /**
  62263. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  62264. */
  62265. get: function () {
  62266. return this.imageProcessingConfiguration.colorCurves;
  62267. },
  62268. /**
  62269. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  62270. */
  62271. set: function (value) {
  62272. this.imageProcessingConfiguration.colorCurves = value;
  62273. },
  62274. enumerable: true,
  62275. configurable: true
  62276. });
  62277. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  62278. /**
  62279. * Gets wether the color curves effect is enabled.
  62280. */
  62281. get: function () {
  62282. return this.imageProcessingConfiguration.colorCurvesEnabled;
  62283. },
  62284. /**
  62285. * Sets wether the color curves effect is enabled.
  62286. */
  62287. set: function (value) {
  62288. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  62289. },
  62290. enumerable: true,
  62291. configurable: true
  62292. });
  62293. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  62294. /**
  62295. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  62296. */
  62297. get: function () {
  62298. return this.imageProcessingConfiguration.colorGradingTexture;
  62299. },
  62300. /**
  62301. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  62302. */
  62303. set: function (value) {
  62304. this.imageProcessingConfiguration.colorGradingTexture = value;
  62305. },
  62306. enumerable: true,
  62307. configurable: true
  62308. });
  62309. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  62310. /**
  62311. * Gets wether the color grading effect is enabled.
  62312. */
  62313. get: function () {
  62314. return this.imageProcessingConfiguration.colorGradingEnabled;
  62315. },
  62316. /**
  62317. * Gets wether the color grading effect is enabled.
  62318. */
  62319. set: function (value) {
  62320. this.imageProcessingConfiguration.colorGradingEnabled = value;
  62321. },
  62322. enumerable: true,
  62323. configurable: true
  62324. });
  62325. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  62326. /**
  62327. * Gets exposure used in the effect.
  62328. */
  62329. get: function () {
  62330. return this.imageProcessingConfiguration.exposure;
  62331. },
  62332. /**
  62333. * Sets exposure used in the effect.
  62334. */
  62335. set: function (value) {
  62336. this.imageProcessingConfiguration.exposure = value;
  62337. },
  62338. enumerable: true,
  62339. configurable: true
  62340. });
  62341. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  62342. /**
  62343. * Gets wether tonemapping is enabled or not.
  62344. */
  62345. get: function () {
  62346. return this._imageProcessingConfiguration.toneMappingEnabled;
  62347. },
  62348. /**
  62349. * Sets wether tonemapping is enabled or not
  62350. */
  62351. set: function (value) {
  62352. this._imageProcessingConfiguration.toneMappingEnabled = value;
  62353. },
  62354. enumerable: true,
  62355. configurable: true
  62356. });
  62357. ;
  62358. ;
  62359. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  62360. /**
  62361. * Gets contrast used in the effect.
  62362. */
  62363. get: function () {
  62364. return this.imageProcessingConfiguration.contrast;
  62365. },
  62366. /**
  62367. * Sets contrast used in the effect.
  62368. */
  62369. set: function (value) {
  62370. this.imageProcessingConfiguration.contrast = value;
  62371. },
  62372. enumerable: true,
  62373. configurable: true
  62374. });
  62375. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  62376. /**
  62377. * Gets Vignette stretch size.
  62378. */
  62379. get: function () {
  62380. return this.imageProcessingConfiguration.vignetteStretch;
  62381. },
  62382. /**
  62383. * Sets Vignette stretch size.
  62384. */
  62385. set: function (value) {
  62386. this.imageProcessingConfiguration.vignetteStretch = value;
  62387. },
  62388. enumerable: true,
  62389. configurable: true
  62390. });
  62391. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  62392. /**
  62393. * Gets Vignette centre X Offset.
  62394. */
  62395. get: function () {
  62396. return this.imageProcessingConfiguration.vignetteCentreX;
  62397. },
  62398. /**
  62399. * Sets Vignette centre X Offset.
  62400. */
  62401. set: function (value) {
  62402. this.imageProcessingConfiguration.vignetteCentreX = value;
  62403. },
  62404. enumerable: true,
  62405. configurable: true
  62406. });
  62407. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  62408. /**
  62409. * Gets Vignette centre Y Offset.
  62410. */
  62411. get: function () {
  62412. return this.imageProcessingConfiguration.vignetteCentreY;
  62413. },
  62414. /**
  62415. * Sets Vignette centre Y Offset.
  62416. */
  62417. set: function (value) {
  62418. this.imageProcessingConfiguration.vignetteCentreY = value;
  62419. },
  62420. enumerable: true,
  62421. configurable: true
  62422. });
  62423. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  62424. /**
  62425. * Gets Vignette weight or intensity of the vignette effect.
  62426. */
  62427. get: function () {
  62428. return this.imageProcessingConfiguration.vignetteWeight;
  62429. },
  62430. /**
  62431. * Sets Vignette weight or intensity of the vignette effect.
  62432. */
  62433. set: function (value) {
  62434. this.imageProcessingConfiguration.vignetteWeight = value;
  62435. },
  62436. enumerable: true,
  62437. configurable: true
  62438. });
  62439. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  62440. /**
  62441. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  62442. * if vignetteEnabled is set to true.
  62443. */
  62444. get: function () {
  62445. return this.imageProcessingConfiguration.vignetteColor;
  62446. },
  62447. /**
  62448. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  62449. * if vignetteEnabled is set to true.
  62450. */
  62451. set: function (value) {
  62452. this.imageProcessingConfiguration.vignetteColor = value;
  62453. },
  62454. enumerable: true,
  62455. configurable: true
  62456. });
  62457. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  62458. /**
  62459. * Gets Camera field of view used by the Vignette effect.
  62460. */
  62461. get: function () {
  62462. return this.imageProcessingConfiguration.vignetteCameraFov;
  62463. },
  62464. /**
  62465. * Sets Camera field of view used by the Vignette effect.
  62466. */
  62467. set: function (value) {
  62468. this.imageProcessingConfiguration.vignetteCameraFov = value;
  62469. },
  62470. enumerable: true,
  62471. configurable: true
  62472. });
  62473. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  62474. /**
  62475. * Gets the vignette blend mode allowing different kind of effect.
  62476. */
  62477. get: function () {
  62478. return this.imageProcessingConfiguration.vignetteBlendMode;
  62479. },
  62480. /**
  62481. * Sets the vignette blend mode allowing different kind of effect.
  62482. */
  62483. set: function (value) {
  62484. this.imageProcessingConfiguration.vignetteBlendMode = value;
  62485. },
  62486. enumerable: true,
  62487. configurable: true
  62488. });
  62489. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  62490. /**
  62491. * Gets wether the vignette effect is enabled.
  62492. */
  62493. get: function () {
  62494. return this.imageProcessingConfiguration.vignetteEnabled;
  62495. },
  62496. /**
  62497. * Sets wether the vignette effect is enabled.
  62498. */
  62499. set: function (value) {
  62500. this.imageProcessingConfiguration.vignetteEnabled = value;
  62501. },
  62502. enumerable: true,
  62503. configurable: true
  62504. });
  62505. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  62506. /**
  62507. * Gets wether the input of the processing is in Gamma or Linear Space.
  62508. */
  62509. get: function () {
  62510. return this._fromLinearSpace;
  62511. },
  62512. /**
  62513. * Sets wether the input of the processing is in Gamma or Linear Space.
  62514. */
  62515. set: function (value) {
  62516. if (this._fromLinearSpace === value) {
  62517. return;
  62518. }
  62519. this._fromLinearSpace = value;
  62520. this._updateParameters();
  62521. },
  62522. enumerable: true,
  62523. configurable: true
  62524. });
  62525. ImageProcessingPostProcess.prototype.getClassName = function () {
  62526. return "ImageProcessingPostProcess";
  62527. };
  62528. ImageProcessingPostProcess.prototype._updateParameters = function () {
  62529. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  62530. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  62531. var defines = "";
  62532. for (var define in this._defines) {
  62533. if (this._defines[define]) {
  62534. defines += "#define " + define + ";\r\n";
  62535. }
  62536. }
  62537. var samplers = ["textureSampler"];
  62538. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  62539. var uniforms = ["scale"];
  62540. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  62541. this.updateEffect(defines, uniforms, samplers);
  62542. };
  62543. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  62544. _super.prototype.dispose.call(this, camera);
  62545. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  62546. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  62547. }
  62548. this.imageProcessingConfiguration.applyByPostProcess = false;
  62549. };
  62550. __decorate([
  62551. BABYLON.serialize()
  62552. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  62553. return ImageProcessingPostProcess;
  62554. }(BABYLON.PostProcess));
  62555. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  62556. })(BABYLON || (BABYLON = {}));
  62557. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  62558. var BABYLON;
  62559. (function (BABYLON) {
  62560. var BlurPostProcess = /** @class */ (function (_super) {
  62561. __extends(BlurPostProcess, _super);
  62562. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  62563. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  62564. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62565. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  62566. _this.direction = direction;
  62567. _this._packedFloat = false;
  62568. _this.onApplyObservable.add(function (effect) {
  62569. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  62570. });
  62571. _this.kernel = kernel;
  62572. return _this;
  62573. }
  62574. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  62575. /**
  62576. * Gets the length in pixels of the blur sample region
  62577. */
  62578. get: function () {
  62579. return this._idealKernel;
  62580. },
  62581. /**
  62582. * Sets the length in pixels of the blur sample region
  62583. */
  62584. set: function (v) {
  62585. if (this._idealKernel === v) {
  62586. return;
  62587. }
  62588. v = Math.max(v, 1);
  62589. this._idealKernel = v;
  62590. this._kernel = this._nearestBestKernel(v);
  62591. this._updateParameters();
  62592. },
  62593. enumerable: true,
  62594. configurable: true
  62595. });
  62596. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  62597. /**
  62598. * Gets wether or not the blur is unpacking/repacking floats
  62599. */
  62600. get: function () {
  62601. return this._packedFloat;
  62602. },
  62603. /**
  62604. * Sets wether or not the blur needs to unpack/repack floats
  62605. */
  62606. set: function (v) {
  62607. if (this._packedFloat === v) {
  62608. return;
  62609. }
  62610. this._packedFloat = v;
  62611. this._updateParameters();
  62612. },
  62613. enumerable: true,
  62614. configurable: true
  62615. });
  62616. BlurPostProcess.prototype._updateParameters = function () {
  62617. // Generate sampling offsets and weights
  62618. var N = this._kernel;
  62619. var centerIndex = (N - 1) / 2;
  62620. // Generate Gaussian sampling weights over kernel
  62621. var offsets = [];
  62622. var weights = [];
  62623. var totalWeight = 0;
  62624. for (var i = 0; i < N; i++) {
  62625. var u = i / (N - 1);
  62626. var w = this._gaussianWeight(u * 2.0 - 1);
  62627. offsets[i] = (i - centerIndex);
  62628. weights[i] = w;
  62629. totalWeight += w;
  62630. }
  62631. // Normalize weights
  62632. for (var i = 0; i < weights.length; i++) {
  62633. weights[i] /= totalWeight;
  62634. }
  62635. // Optimize: combine samples to take advantage of hardware linear sampling
  62636. // Walk from left to center, combining pairs (symmetrically)
  62637. var linearSamplingWeights = [];
  62638. var linearSamplingOffsets = [];
  62639. var linearSamplingMap = [];
  62640. for (var i = 0; i <= centerIndex; i += 2) {
  62641. var j = Math.min(i + 1, Math.floor(centerIndex));
  62642. var singleCenterSample = i === j;
  62643. if (singleCenterSample) {
  62644. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  62645. }
  62646. else {
  62647. var sharedCell = j === centerIndex;
  62648. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  62649. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  62650. if (offsetLinear === 0) {
  62651. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  62652. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  62653. }
  62654. else {
  62655. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  62656. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  62657. }
  62658. }
  62659. }
  62660. for (var i = 0; i < linearSamplingMap.length; i++) {
  62661. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  62662. linearSamplingWeights[i] = linearSamplingMap[i].w;
  62663. }
  62664. // Replace with optimized
  62665. offsets = linearSamplingOffsets;
  62666. weights = linearSamplingWeights;
  62667. // Generate shaders
  62668. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  62669. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  62670. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  62671. var defines = "";
  62672. for (var i = 0; i < varyingCount; i++) {
  62673. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  62674. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  62675. }
  62676. var depCount = 0;
  62677. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  62678. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  62679. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  62680. depCount++;
  62681. }
  62682. if (this.packedFloat) {
  62683. defines += "#define PACKEDFLOAT 1";
  62684. }
  62685. this.updateEffect(defines, null, null, {
  62686. varyingCount: varyingCount,
  62687. depCount: depCount
  62688. });
  62689. };
  62690. /**
  62691. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  62692. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  62693. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  62694. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  62695. * The gaps between physical kernels are compensated for in the weighting of the samples
  62696. * @param idealKernel Ideal blur kernel.
  62697. * @return Nearest best kernel.
  62698. */
  62699. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  62700. var v = Math.round(idealKernel);
  62701. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  62702. var k = _a[_i];
  62703. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  62704. return Math.max(k, 3);
  62705. }
  62706. }
  62707. return Math.max(v, 3);
  62708. };
  62709. /**
  62710. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  62711. * @param x The point on the Gaussian distribution to sample.
  62712. * @return the value of the Gaussian function at x.
  62713. */
  62714. BlurPostProcess.prototype._gaussianWeight = function (x) {
  62715. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  62716. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  62717. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  62718. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  62719. // truncated at around 1.3% of peak strength.
  62720. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  62721. var sigma = (1 / 3);
  62722. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  62723. var exponent = -((x * x) / (2.0 * sigma * sigma));
  62724. var weight = (1.0 / denominator) * Math.exp(exponent);
  62725. return weight;
  62726. };
  62727. /**
  62728. * Generates a string that can be used as a floating point number in GLSL.
  62729. * @param x Value to print.
  62730. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  62731. * @return GLSL float string.
  62732. */
  62733. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  62734. if (decimalFigures === void 0) { decimalFigures = 8; }
  62735. return x.toFixed(decimalFigures).replace(/0+$/, '');
  62736. };
  62737. return BlurPostProcess;
  62738. }(BABYLON.PostProcess));
  62739. BABYLON.BlurPostProcess = BlurPostProcess;
  62740. })(BABYLON || (BABYLON = {}));
  62741. //# sourceMappingURL=babylon.blurPostProcess.js.map
  62742. var BABYLON;
  62743. (function (BABYLON) {
  62744. var Bone = /** @class */ (function (_super) {
  62745. __extends(Bone, _super);
  62746. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  62747. if (parentBone === void 0) { parentBone = null; }
  62748. if (localMatrix === void 0) { localMatrix = null; }
  62749. if (restPose === void 0) { restPose = null; }
  62750. if (baseMatrix === void 0) { baseMatrix = null; }
  62751. if (index === void 0) { index = null; }
  62752. var _this = _super.call(this, name, skeleton.getScene()) || this;
  62753. _this.name = name;
  62754. _this.children = new Array();
  62755. _this.animations = new Array();
  62756. // Set this value to map this bone to a different index in the transform matrices.
  62757. // Set this value to -1 to exclude the bone from the transform matrices.
  62758. _this._index = null;
  62759. _this._worldTransform = new BABYLON.Matrix();
  62760. _this._absoluteTransform = new BABYLON.Matrix();
  62761. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  62762. _this._scaleMatrix = BABYLON.Matrix.Identity();
  62763. _this._scaleVector = BABYLON.Vector3.One();
  62764. _this._negateScaleChildren = BABYLON.Vector3.One();
  62765. _this._scalingDeterminant = 1;
  62766. _this._skeleton = skeleton;
  62767. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  62768. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  62769. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  62770. _this._index = index;
  62771. skeleton.bones.push(_this);
  62772. _this.setParent(parentBone, false);
  62773. _this._updateDifferenceMatrix();
  62774. return _this;
  62775. }
  62776. Object.defineProperty(Bone.prototype, "_matrix", {
  62777. get: function () {
  62778. return this._localMatrix;
  62779. },
  62780. set: function (val) {
  62781. if (this._localMatrix) {
  62782. this._localMatrix.copyFrom(val);
  62783. }
  62784. else {
  62785. this._localMatrix = val;
  62786. }
  62787. },
  62788. enumerable: true,
  62789. configurable: true
  62790. });
  62791. // Members
  62792. Bone.prototype.getSkeleton = function () {
  62793. return this._skeleton;
  62794. };
  62795. Bone.prototype.getParent = function () {
  62796. return this._parent;
  62797. };
  62798. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  62799. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  62800. if (this._parent === parent) {
  62801. return;
  62802. }
  62803. if (this._parent) {
  62804. var index = this._parent.children.indexOf(this);
  62805. if (index !== -1) {
  62806. this._parent.children.splice(index, 1);
  62807. }
  62808. }
  62809. this._parent = parent;
  62810. if (this._parent) {
  62811. this._parent.children.push(this);
  62812. }
  62813. if (updateDifferenceMatrix) {
  62814. this._updateDifferenceMatrix();
  62815. }
  62816. };
  62817. Bone.prototype.getLocalMatrix = function () {
  62818. return this._localMatrix;
  62819. };
  62820. Bone.prototype.getBaseMatrix = function () {
  62821. return this._baseMatrix;
  62822. };
  62823. Bone.prototype.getRestPose = function () {
  62824. return this._restPose;
  62825. };
  62826. Bone.prototype.returnToRest = function () {
  62827. this.updateMatrix(this._restPose.clone());
  62828. };
  62829. Bone.prototype.getWorldMatrix = function () {
  62830. return this._worldTransform;
  62831. };
  62832. Bone.prototype.getInvertedAbsoluteTransform = function () {
  62833. return this._invertedAbsoluteTransform;
  62834. };
  62835. Bone.prototype.getAbsoluteTransform = function () {
  62836. return this._absoluteTransform;
  62837. };
  62838. Object.defineProperty(Bone.prototype, "position", {
  62839. // Properties (matches AbstractMesh properties)
  62840. get: function () {
  62841. return this.getPosition();
  62842. },
  62843. set: function (newPosition) {
  62844. this.setPosition(newPosition);
  62845. },
  62846. enumerable: true,
  62847. configurable: true
  62848. });
  62849. Object.defineProperty(Bone.prototype, "rotation", {
  62850. get: function () {
  62851. return this.getRotation();
  62852. },
  62853. set: function (newRotation) {
  62854. this.setRotation(newRotation);
  62855. },
  62856. enumerable: true,
  62857. configurable: true
  62858. });
  62859. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  62860. get: function () {
  62861. return this.getRotationQuaternion();
  62862. },
  62863. set: function (newRotation) {
  62864. this.setRotationQuaternion(newRotation);
  62865. },
  62866. enumerable: true,
  62867. configurable: true
  62868. });
  62869. Object.defineProperty(Bone.prototype, "scaling", {
  62870. get: function () {
  62871. return this.getScale();
  62872. },
  62873. set: function (newScaling) {
  62874. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  62875. },
  62876. enumerable: true,
  62877. configurable: true
  62878. });
  62879. // Methods
  62880. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  62881. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  62882. this._baseMatrix = matrix.clone();
  62883. this._localMatrix = matrix.clone();
  62884. this._skeleton._markAsDirty();
  62885. if (updateDifferenceMatrix) {
  62886. this._updateDifferenceMatrix();
  62887. }
  62888. };
  62889. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  62890. if (!rootMatrix) {
  62891. rootMatrix = this._baseMatrix;
  62892. }
  62893. if (this._parent) {
  62894. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  62895. }
  62896. else {
  62897. this._absoluteTransform.copyFrom(rootMatrix);
  62898. }
  62899. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  62900. for (var index = 0; index < this.children.length; index++) {
  62901. this.children[index]._updateDifferenceMatrix();
  62902. }
  62903. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  62904. };
  62905. Bone.prototype.markAsDirty = function () {
  62906. this._currentRenderId++;
  62907. this._skeleton._markAsDirty();
  62908. };
  62909. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  62910. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  62911. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  62912. // all animation may be coming from a library skeleton, so may need to create animation
  62913. if (this.animations.length === 0) {
  62914. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  62915. this.animations[0].setKeys([]);
  62916. }
  62917. // get animation info / verify there is such a range from the source bone
  62918. var sourceRange = source.animations[0].getRange(rangeName);
  62919. if (!sourceRange) {
  62920. return false;
  62921. }
  62922. var from = sourceRange.from;
  62923. var to = sourceRange.to;
  62924. var sourceKeys = source.animations[0].getKeys();
  62925. // rescaling prep
  62926. var sourceBoneLength = source.length;
  62927. var sourceParent = source.getParent();
  62928. var parent = this.getParent();
  62929. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  62930. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  62931. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  62932. var destKeys = this.animations[0].getKeys();
  62933. // loop vars declaration
  62934. var orig;
  62935. var origTranslation;
  62936. var mat;
  62937. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  62938. orig = sourceKeys[key];
  62939. if (orig.frame >= from && orig.frame <= to) {
  62940. if (rescaleAsRequired) {
  62941. mat = orig.value.clone();
  62942. // scale based on parent ratio, when bone has parent
  62943. if (parentScalingReqd) {
  62944. origTranslation = mat.getTranslation();
  62945. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  62946. // scale based on skeleton dimension ratio when root bone, and value is passed
  62947. }
  62948. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  62949. origTranslation = mat.getTranslation();
  62950. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  62951. // use original when root bone, and no data for skelDimensionsRatio
  62952. }
  62953. else {
  62954. mat = orig.value;
  62955. }
  62956. }
  62957. else {
  62958. mat = orig.value;
  62959. }
  62960. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  62961. }
  62962. }
  62963. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  62964. return true;
  62965. };
  62966. /**
  62967. * Translate the bone in local or world space.
  62968. * @param vec The amount to translate the bone.
  62969. * @param space The space that the translation is in.
  62970. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62971. */
  62972. Bone.prototype.translate = function (vec, space, mesh) {
  62973. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62974. var lm = this.getLocalMatrix();
  62975. if (space == BABYLON.Space.LOCAL) {
  62976. lm.m[12] += vec.x;
  62977. lm.m[13] += vec.y;
  62978. lm.m[14] += vec.z;
  62979. }
  62980. else {
  62981. var wm = null;
  62982. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  62983. if (mesh) {
  62984. wm = mesh.getWorldMatrix();
  62985. }
  62986. this._skeleton.computeAbsoluteTransforms();
  62987. var tmat = Bone._tmpMats[0];
  62988. var tvec = Bone._tmpVecs[0];
  62989. if (this._parent) {
  62990. if (mesh && wm) {
  62991. tmat.copyFrom(this._parent.getAbsoluteTransform());
  62992. tmat.multiplyToRef(wm, tmat);
  62993. }
  62994. else {
  62995. tmat.copyFrom(this._parent.getAbsoluteTransform());
  62996. }
  62997. }
  62998. tmat.m[12] = 0;
  62999. tmat.m[13] = 0;
  63000. tmat.m[14] = 0;
  63001. tmat.invert();
  63002. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  63003. lm.m[12] += tvec.x;
  63004. lm.m[13] += tvec.y;
  63005. lm.m[14] += tvec.z;
  63006. }
  63007. this.markAsDirty();
  63008. };
  63009. /**
  63010. * Set the postion of the bone in local or world space.
  63011. * @param position The position to set the bone.
  63012. * @param space The space that the position is in.
  63013. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63014. */
  63015. Bone.prototype.setPosition = function (position, space, mesh) {
  63016. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63017. var lm = this.getLocalMatrix();
  63018. if (space == BABYLON.Space.LOCAL) {
  63019. lm.m[12] = position.x;
  63020. lm.m[13] = position.y;
  63021. lm.m[14] = position.z;
  63022. }
  63023. else {
  63024. var wm = null;
  63025. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  63026. if (mesh) {
  63027. wm = mesh.getWorldMatrix();
  63028. }
  63029. this._skeleton.computeAbsoluteTransforms();
  63030. var tmat = Bone._tmpMats[0];
  63031. var vec = Bone._tmpVecs[0];
  63032. if (this._parent) {
  63033. if (mesh && wm) {
  63034. tmat.copyFrom(this._parent.getAbsoluteTransform());
  63035. tmat.multiplyToRef(wm, tmat);
  63036. }
  63037. else {
  63038. tmat.copyFrom(this._parent.getAbsoluteTransform());
  63039. }
  63040. }
  63041. tmat.invert();
  63042. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  63043. lm.m[12] = vec.x;
  63044. lm.m[13] = vec.y;
  63045. lm.m[14] = vec.z;
  63046. }
  63047. this.markAsDirty();
  63048. };
  63049. /**
  63050. * Set the absolute postion of the bone (world space).
  63051. * @param position The position to set the bone.
  63052. * @param mesh The mesh that this bone is attached to.
  63053. */
  63054. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  63055. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  63056. };
  63057. /**
  63058. * Set the scale of the bone on the x, y and z axes.
  63059. * @param x The scale of the bone on the x axis.
  63060. * @param x The scale of the bone on the y axis.
  63061. * @param z The scale of the bone on the z axis.
  63062. * @param scaleChildren Set this to true if children of the bone should be scaled.
  63063. */
  63064. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  63065. if (scaleChildren === void 0) { scaleChildren = false; }
  63066. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  63067. if (!scaleChildren) {
  63068. this._negateScaleChildren.x = 1 / x;
  63069. this._negateScaleChildren.y = 1 / y;
  63070. this._negateScaleChildren.z = 1 / z;
  63071. }
  63072. this._syncScaleVector();
  63073. }
  63074. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  63075. };
  63076. /**
  63077. * Scale the bone on the x, y and z axes.
  63078. * @param x The amount to scale the bone on the x axis.
  63079. * @param x The amount to scale the bone on the y axis.
  63080. * @param z The amount to scale the bone on the z axis.
  63081. * @param scaleChildren Set this to true if children of the bone should be scaled.
  63082. */
  63083. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  63084. if (scaleChildren === void 0) { scaleChildren = false; }
  63085. var locMat = this.getLocalMatrix();
  63086. var origLocMat = Bone._tmpMats[0];
  63087. origLocMat.copyFrom(locMat);
  63088. var origLocMatInv = Bone._tmpMats[1];
  63089. origLocMatInv.copyFrom(origLocMat);
  63090. origLocMatInv.invert();
  63091. var scaleMat = Bone._tmpMats[2];
  63092. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  63093. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  63094. this._scaleVector.x *= x;
  63095. this._scaleVector.y *= y;
  63096. this._scaleVector.z *= z;
  63097. locMat.multiplyToRef(origLocMatInv, locMat);
  63098. locMat.multiplyToRef(scaleMat, locMat);
  63099. locMat.multiplyToRef(origLocMat, locMat);
  63100. var parent = this.getParent();
  63101. if (parent) {
  63102. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  63103. }
  63104. else {
  63105. this.getAbsoluteTransform().copyFrom(locMat);
  63106. }
  63107. var len = this.children.length;
  63108. scaleMat.invert();
  63109. for (var i = 0; i < len; i++) {
  63110. var child = this.children[i];
  63111. var cm = child.getLocalMatrix();
  63112. cm.multiplyToRef(scaleMat, cm);
  63113. var lm = child.getLocalMatrix();
  63114. lm.m[12] *= x;
  63115. lm.m[13] *= y;
  63116. lm.m[14] *= z;
  63117. }
  63118. this.computeAbsoluteTransforms();
  63119. if (scaleChildren) {
  63120. for (var i = 0; i < len; i++) {
  63121. this.children[i].scale(x, y, z, scaleChildren);
  63122. }
  63123. }
  63124. this.markAsDirty();
  63125. };
  63126. /**
  63127. * Set the yaw, pitch, and roll of the bone in local or world space.
  63128. * @param yaw The rotation of the bone on the y axis.
  63129. * @param pitch The rotation of the bone on the x axis.
  63130. * @param roll The rotation of the bone on the z axis.
  63131. * @param space The space that the axes of rotation are in.
  63132. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63133. */
  63134. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  63135. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63136. var rotMat = Bone._tmpMats[0];
  63137. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  63138. var rotMatInv = Bone._tmpMats[1];
  63139. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  63140. rotMatInv.multiplyToRef(rotMat, rotMat);
  63141. this._rotateWithMatrix(rotMat, space, mesh);
  63142. };
  63143. /**
  63144. * Rotate the bone on an axis in local or world space.
  63145. * @param axis The axis to rotate the bone on.
  63146. * @param amount The amount to rotate the bone.
  63147. * @param space The space that the axis is in.
  63148. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63149. */
  63150. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  63151. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63152. var rmat = Bone._tmpMats[0];
  63153. rmat.m[12] = 0;
  63154. rmat.m[13] = 0;
  63155. rmat.m[14] = 0;
  63156. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  63157. this._rotateWithMatrix(rmat, space, mesh);
  63158. };
  63159. /**
  63160. * Set the rotation of the bone to a particular axis angle in local or world space.
  63161. * @param axis The axis to rotate the bone on.
  63162. * @param angle The angle that the bone should be rotated to.
  63163. * @param space The space that the axis is in.
  63164. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63165. */
  63166. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  63167. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63168. var rotMat = Bone._tmpMats[0];
  63169. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  63170. var rotMatInv = Bone._tmpMats[1];
  63171. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  63172. rotMatInv.multiplyToRef(rotMat, rotMat);
  63173. this._rotateWithMatrix(rotMat, space, mesh);
  63174. };
  63175. /**
  63176. * Set the euler rotation of the bone in local of world space.
  63177. * @param rotation The euler rotation that the bone should be set to.
  63178. * @param space The space that the rotation is in.
  63179. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63180. */
  63181. Bone.prototype.setRotation = function (rotation, space, mesh) {
  63182. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63183. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  63184. };
  63185. /**
  63186. * Set the quaternion rotation of the bone in local of world space.
  63187. * @param quat The quaternion rotation that the bone should be set to.
  63188. * @param space The space that the rotation is in.
  63189. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63190. */
  63191. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  63192. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63193. var rotMatInv = Bone._tmpMats[0];
  63194. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  63195. var rotMat = Bone._tmpMats[1];
  63196. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  63197. rotMatInv.multiplyToRef(rotMat, rotMat);
  63198. this._rotateWithMatrix(rotMat, space, mesh);
  63199. };
  63200. /**
  63201. * Set the rotation matrix of the bone in local of world space.
  63202. * @param rotMat The rotation matrix that the bone should be set to.
  63203. * @param space The space that the rotation is in.
  63204. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63205. */
  63206. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  63207. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63208. var rotMatInv = Bone._tmpMats[0];
  63209. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  63210. var rotMat2 = Bone._tmpMats[1];
  63211. rotMat2.copyFrom(rotMat);
  63212. rotMatInv.multiplyToRef(rotMat, rotMat2);
  63213. this._rotateWithMatrix(rotMat2, space, mesh);
  63214. };
  63215. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  63216. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63217. var lmat = this.getLocalMatrix();
  63218. var lx = lmat.m[12];
  63219. var ly = lmat.m[13];
  63220. var lz = lmat.m[14];
  63221. var parent = this.getParent();
  63222. var parentScale = Bone._tmpMats[3];
  63223. var parentScaleInv = Bone._tmpMats[4];
  63224. if (parent) {
  63225. if (space == BABYLON.Space.WORLD) {
  63226. if (mesh) {
  63227. parentScale.copyFrom(mesh.getWorldMatrix());
  63228. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  63229. }
  63230. else {
  63231. parentScale.copyFrom(parent.getAbsoluteTransform());
  63232. }
  63233. }
  63234. else {
  63235. parentScale = parent._scaleMatrix;
  63236. }
  63237. parentScaleInv.copyFrom(parentScale);
  63238. parentScaleInv.invert();
  63239. lmat.multiplyToRef(parentScale, lmat);
  63240. lmat.multiplyToRef(rmat, lmat);
  63241. lmat.multiplyToRef(parentScaleInv, lmat);
  63242. }
  63243. else {
  63244. if (space == BABYLON.Space.WORLD && mesh) {
  63245. parentScale.copyFrom(mesh.getWorldMatrix());
  63246. parentScaleInv.copyFrom(parentScale);
  63247. parentScaleInv.invert();
  63248. lmat.multiplyToRef(parentScale, lmat);
  63249. lmat.multiplyToRef(rmat, lmat);
  63250. lmat.multiplyToRef(parentScaleInv, lmat);
  63251. }
  63252. else {
  63253. lmat.multiplyToRef(rmat, lmat);
  63254. }
  63255. }
  63256. lmat.m[12] = lx;
  63257. lmat.m[13] = ly;
  63258. lmat.m[14] = lz;
  63259. this.computeAbsoluteTransforms();
  63260. this.markAsDirty();
  63261. };
  63262. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  63263. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63264. if (space == BABYLON.Space.WORLD) {
  63265. var scaleMatrix = Bone._tmpMats[2];
  63266. scaleMatrix.copyFrom(this._scaleMatrix);
  63267. rotMatInv.copyFrom(this.getAbsoluteTransform());
  63268. if (mesh) {
  63269. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  63270. var meshScale = Bone._tmpMats[3];
  63271. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  63272. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  63273. }
  63274. rotMatInv.invert();
  63275. scaleMatrix.m[0] *= this._scalingDeterminant;
  63276. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  63277. }
  63278. else {
  63279. rotMatInv.copyFrom(this.getLocalMatrix());
  63280. rotMatInv.invert();
  63281. var scaleMatrix = Bone._tmpMats[2];
  63282. scaleMatrix.copyFrom(this._scaleMatrix);
  63283. if (this._parent) {
  63284. var pscaleMatrix = Bone._tmpMats[3];
  63285. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  63286. pscaleMatrix.invert();
  63287. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  63288. }
  63289. else {
  63290. scaleMatrix.m[0] *= this._scalingDeterminant;
  63291. }
  63292. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  63293. }
  63294. };
  63295. /**
  63296. * Get the scale of the bone
  63297. * @returns the scale of the bone
  63298. */
  63299. Bone.prototype.getScale = function () {
  63300. return this._scaleVector.clone();
  63301. };
  63302. /**
  63303. * Copy the scale of the bone to a vector3.
  63304. * @param result The vector3 to copy the scale to
  63305. */
  63306. Bone.prototype.getScaleToRef = function (result) {
  63307. result.copyFrom(this._scaleVector);
  63308. };
  63309. /**
  63310. * Get the position of the bone in local or world space.
  63311. * @param space The space that the returned position is in.
  63312. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63313. * @returns The position of the bone
  63314. */
  63315. Bone.prototype.getPosition = function (space, mesh) {
  63316. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63317. if (mesh === void 0) { mesh = null; }
  63318. var pos = BABYLON.Vector3.Zero();
  63319. this.getPositionToRef(space, mesh, pos);
  63320. return pos;
  63321. };
  63322. /**
  63323. * Copy the position of the bone to a vector3 in local or world space.
  63324. * @param space The space that the returned position is in.
  63325. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63326. * @param result The vector3 to copy the position to.
  63327. */
  63328. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  63329. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63330. if (space == BABYLON.Space.LOCAL) {
  63331. var lm = this.getLocalMatrix();
  63332. result.x = lm.m[12];
  63333. result.y = lm.m[13];
  63334. result.z = lm.m[14];
  63335. }
  63336. else {
  63337. var wm = null;
  63338. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  63339. if (mesh) {
  63340. wm = mesh.getWorldMatrix();
  63341. }
  63342. this._skeleton.computeAbsoluteTransforms();
  63343. var tmat = Bone._tmpMats[0];
  63344. if (mesh && wm) {
  63345. tmat.copyFrom(this.getAbsoluteTransform());
  63346. tmat.multiplyToRef(wm, tmat);
  63347. }
  63348. else {
  63349. tmat = this.getAbsoluteTransform();
  63350. }
  63351. result.x = tmat.m[12];
  63352. result.y = tmat.m[13];
  63353. result.z = tmat.m[14];
  63354. }
  63355. };
  63356. /**
  63357. * Get the absolute position of the bone (world space).
  63358. * @param mesh The mesh that this bone is attached to.
  63359. * @returns The absolute position of the bone
  63360. */
  63361. Bone.prototype.getAbsolutePosition = function (mesh) {
  63362. if (mesh === void 0) { mesh = null; }
  63363. var pos = BABYLON.Vector3.Zero();
  63364. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  63365. return pos;
  63366. };
  63367. /**
  63368. * Copy the absolute position of the bone (world space) to the result param.
  63369. * @param mesh The mesh that this bone is attached to.
  63370. * @param result The vector3 to copy the absolute position to.
  63371. */
  63372. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  63373. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  63374. };
  63375. /**
  63376. * Compute the absolute transforms of this bone and its children.
  63377. */
  63378. Bone.prototype.computeAbsoluteTransforms = function () {
  63379. if (this._parent) {
  63380. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  63381. }
  63382. else {
  63383. this._absoluteTransform.copyFrom(this._localMatrix);
  63384. var poseMatrix = this._skeleton.getPoseMatrix();
  63385. if (poseMatrix) {
  63386. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  63387. }
  63388. }
  63389. var children = this.children;
  63390. var len = children.length;
  63391. for (var i = 0; i < len; i++) {
  63392. children[i].computeAbsoluteTransforms();
  63393. }
  63394. };
  63395. Bone.prototype._syncScaleVector = function () {
  63396. var lm = this.getLocalMatrix();
  63397. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  63398. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  63399. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  63400. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  63401. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  63402. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  63403. this._scaleVector.x = xs * Math.sqrt(xsq);
  63404. this._scaleVector.y = ys * Math.sqrt(ysq);
  63405. this._scaleVector.z = zs * Math.sqrt(zsq);
  63406. if (this._parent) {
  63407. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  63408. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  63409. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  63410. }
  63411. 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);
  63412. };
  63413. /**
  63414. * Get the world direction from an axis that is in the local space of the bone.
  63415. * @param localAxis The local direction that is used to compute the world direction.
  63416. * @param mesh The mesh that this bone is attached to.
  63417. * @returns The world direction
  63418. */
  63419. Bone.prototype.getDirection = function (localAxis, mesh) {
  63420. if (mesh === void 0) { mesh = null; }
  63421. var result = BABYLON.Vector3.Zero();
  63422. this.getDirectionToRef(localAxis, mesh, result);
  63423. return result;
  63424. };
  63425. /**
  63426. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  63427. * @param localAxis The local direction that is used to compute the world direction.
  63428. * @param mesh The mesh that this bone is attached to.
  63429. * @param result The vector3 that the world direction will be copied to.
  63430. */
  63431. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  63432. if (mesh === void 0) { mesh = null; }
  63433. var wm = null;
  63434. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  63435. if (mesh) {
  63436. wm = mesh.getWorldMatrix();
  63437. }
  63438. this._skeleton.computeAbsoluteTransforms();
  63439. var mat = Bone._tmpMats[0];
  63440. mat.copyFrom(this.getAbsoluteTransform());
  63441. if (mesh && wm) {
  63442. mat.multiplyToRef(wm, mat);
  63443. }
  63444. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  63445. result.normalize();
  63446. };
  63447. /**
  63448. * Get the euler rotation of the bone in local or world space.
  63449. * @param space The space that the rotation should be in.
  63450. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63451. * @returns The euler rotation
  63452. */
  63453. Bone.prototype.getRotation = function (space, mesh) {
  63454. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63455. if (mesh === void 0) { mesh = null; }
  63456. var result = BABYLON.Vector3.Zero();
  63457. this.getRotationToRef(space, mesh, result);
  63458. return result;
  63459. };
  63460. /**
  63461. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  63462. * @param space The space that the rotation should be in.
  63463. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63464. * @param result The vector3 that the rotation should be copied to.
  63465. */
  63466. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  63467. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63468. if (mesh === void 0) { mesh = null; }
  63469. var quat = Bone._tmpQuat;
  63470. this.getRotationQuaternionToRef(space, mesh, quat);
  63471. quat.toEulerAnglesToRef(result);
  63472. };
  63473. /**
  63474. * Get the quaternion rotation of the bone in either local or world space.
  63475. * @param space The space that the rotation should be in.
  63476. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63477. * @returns The quaternion rotation
  63478. */
  63479. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  63480. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63481. if (mesh === void 0) { mesh = null; }
  63482. var result = BABYLON.Quaternion.Identity();
  63483. this.getRotationQuaternionToRef(space, mesh, result);
  63484. return result;
  63485. };
  63486. /**
  63487. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  63488. * @param space The space that the rotation should be in.
  63489. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63490. * @param result The quaternion that the rotation should be copied to.
  63491. */
  63492. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  63493. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63494. if (mesh === void 0) { mesh = null; }
  63495. if (space == BABYLON.Space.LOCAL) {
  63496. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  63497. }
  63498. else {
  63499. var mat = Bone._tmpMats[0];
  63500. var amat = this.getAbsoluteTransform();
  63501. if (mesh) {
  63502. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  63503. }
  63504. else {
  63505. mat.copyFrom(amat);
  63506. }
  63507. mat.m[0] *= this._scalingDeterminant;
  63508. mat.m[1] *= this._scalingDeterminant;
  63509. mat.m[2] *= this._scalingDeterminant;
  63510. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  63511. }
  63512. };
  63513. /**
  63514. * Get the rotation matrix of the bone in local or world space.
  63515. * @param space The space that the rotation should be in.
  63516. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63517. * @returns The rotation matrix
  63518. */
  63519. Bone.prototype.getRotationMatrix = function (space, mesh) {
  63520. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63521. var result = BABYLON.Matrix.Identity();
  63522. this.getRotationMatrixToRef(space, mesh, result);
  63523. return result;
  63524. };
  63525. /**
  63526. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  63527. * @param space The space that the rotation should be in.
  63528. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63529. * @param result The quaternion that the rotation should be copied to.
  63530. */
  63531. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  63532. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63533. if (space == BABYLON.Space.LOCAL) {
  63534. this.getLocalMatrix().getRotationMatrixToRef(result);
  63535. }
  63536. else {
  63537. var mat = Bone._tmpMats[0];
  63538. var amat = this.getAbsoluteTransform();
  63539. if (mesh) {
  63540. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  63541. }
  63542. else {
  63543. mat.copyFrom(amat);
  63544. }
  63545. mat.m[0] *= this._scalingDeterminant;
  63546. mat.m[1] *= this._scalingDeterminant;
  63547. mat.m[2] *= this._scalingDeterminant;
  63548. mat.getRotationMatrixToRef(result);
  63549. }
  63550. };
  63551. /**
  63552. * Get the world position of a point that is in the local space of the bone.
  63553. * @param position The local position
  63554. * @param mesh The mesh that this bone is attached to.
  63555. * @returns The world position
  63556. */
  63557. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  63558. if (mesh === void 0) { mesh = null; }
  63559. var result = BABYLON.Vector3.Zero();
  63560. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  63561. return result;
  63562. };
  63563. /**
  63564. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  63565. * @param position The local position
  63566. * @param mesh The mesh that this bone is attached to.
  63567. * @param result The vector3 that the world position should be copied to.
  63568. */
  63569. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  63570. if (mesh === void 0) { mesh = null; }
  63571. var wm = null;
  63572. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  63573. if (mesh) {
  63574. wm = mesh.getWorldMatrix();
  63575. }
  63576. this._skeleton.computeAbsoluteTransforms();
  63577. var tmat = Bone._tmpMats[0];
  63578. if (mesh && wm) {
  63579. tmat.copyFrom(this.getAbsoluteTransform());
  63580. tmat.multiplyToRef(wm, tmat);
  63581. }
  63582. else {
  63583. tmat = this.getAbsoluteTransform();
  63584. }
  63585. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  63586. };
  63587. /**
  63588. * Get the local position of a point that is in world space.
  63589. * @param position The world position
  63590. * @param mesh The mesh that this bone is attached to.
  63591. * @returns The local position
  63592. */
  63593. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  63594. if (mesh === void 0) { mesh = null; }
  63595. var result = BABYLON.Vector3.Zero();
  63596. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  63597. return result;
  63598. };
  63599. /**
  63600. * Get the local position of a point that is in world space and copy it to the result param.
  63601. * @param position The world position
  63602. * @param mesh The mesh that this bone is attached to.
  63603. * @param result The vector3 that the local position should be copied to.
  63604. */
  63605. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  63606. if (mesh === void 0) { mesh = null; }
  63607. var wm = null;
  63608. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  63609. if (mesh) {
  63610. wm = mesh.getWorldMatrix();
  63611. }
  63612. this._skeleton.computeAbsoluteTransforms();
  63613. var tmat = Bone._tmpMats[0];
  63614. tmat.copyFrom(this.getAbsoluteTransform());
  63615. if (mesh && wm) {
  63616. tmat.multiplyToRef(wm, tmat);
  63617. }
  63618. tmat.invert();
  63619. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  63620. };
  63621. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63622. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  63623. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  63624. return Bone;
  63625. }(BABYLON.Node));
  63626. BABYLON.Bone = Bone;
  63627. })(BABYLON || (BABYLON = {}));
  63628. //# sourceMappingURL=babylon.bone.js.map
  63629. var BABYLON;
  63630. (function (BABYLON) {
  63631. var BoneIKController = /** @class */ (function () {
  63632. function BoneIKController(mesh, bone, options) {
  63633. this.targetPosition = BABYLON.Vector3.Zero();
  63634. this.poleTargetPosition = BABYLON.Vector3.Zero();
  63635. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  63636. this.poleAngle = 0;
  63637. this.slerpAmount = 1;
  63638. this._bone1Quat = BABYLON.Quaternion.Identity();
  63639. this._bone1Mat = BABYLON.Matrix.Identity();
  63640. this._bone2Ang = Math.PI;
  63641. this._maxAngle = Math.PI;
  63642. this._rightHandedSystem = false;
  63643. this._bendAxis = BABYLON.Vector3.Right();
  63644. this._slerping = false;
  63645. this._adjustRoll = 0;
  63646. this._bone2 = bone;
  63647. this._bone1 = bone.getParent();
  63648. if (!this._bone1) {
  63649. return;
  63650. }
  63651. this.mesh = mesh;
  63652. var bonePos = bone.getPosition();
  63653. if (bone.getAbsoluteTransform().determinant() > 0) {
  63654. this._rightHandedSystem = true;
  63655. this._bendAxis.x = 0;
  63656. this._bendAxis.y = 0;
  63657. this._bendAxis.z = -1;
  63658. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  63659. this._adjustRoll = Math.PI * .5;
  63660. this._bendAxis.z = 1;
  63661. }
  63662. }
  63663. if (this._bone1.length) {
  63664. var boneScale1 = this._bone1.getScale();
  63665. var boneScale2 = this._bone2.getScale();
  63666. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  63667. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  63668. }
  63669. else if (this._bone1.children[0]) {
  63670. mesh.computeWorldMatrix(true);
  63671. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  63672. var pos2 = this._bone2.getAbsolutePosition(mesh);
  63673. var pos3 = this._bone1.getAbsolutePosition(mesh);
  63674. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  63675. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  63676. }
  63677. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  63678. this.maxAngle = Math.PI;
  63679. if (options) {
  63680. if (options.targetMesh) {
  63681. this.targetMesh = options.targetMesh;
  63682. this.targetMesh.computeWorldMatrix(true);
  63683. }
  63684. if (options.poleTargetMesh) {
  63685. this.poleTargetMesh = options.poleTargetMesh;
  63686. this.poleTargetMesh.computeWorldMatrix(true);
  63687. }
  63688. else if (options.poleTargetBone) {
  63689. this.poleTargetBone = options.poleTargetBone;
  63690. }
  63691. else if (this._bone1.getParent()) {
  63692. this.poleTargetBone = this._bone1.getParent();
  63693. }
  63694. if (options.poleTargetLocalOffset) {
  63695. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  63696. }
  63697. if (options.poleAngle) {
  63698. this.poleAngle = options.poleAngle;
  63699. }
  63700. if (options.bendAxis) {
  63701. this._bendAxis.copyFrom(options.bendAxis);
  63702. }
  63703. if (options.maxAngle) {
  63704. this.maxAngle = options.maxAngle;
  63705. }
  63706. if (options.slerpAmount) {
  63707. this.slerpAmount = options.slerpAmount;
  63708. }
  63709. }
  63710. }
  63711. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  63712. get: function () {
  63713. return this._maxAngle;
  63714. },
  63715. set: function (value) {
  63716. this._setMaxAngle(value);
  63717. },
  63718. enumerable: true,
  63719. configurable: true
  63720. });
  63721. BoneIKController.prototype._setMaxAngle = function (ang) {
  63722. if (ang < 0) {
  63723. ang = 0;
  63724. }
  63725. if (ang > Math.PI || ang == undefined) {
  63726. ang = Math.PI;
  63727. }
  63728. this._maxAngle = ang;
  63729. var a = this._bone1Length;
  63730. var b = this._bone2Length;
  63731. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  63732. };
  63733. BoneIKController.prototype.update = function () {
  63734. var bone1 = this._bone1;
  63735. if (!bone1) {
  63736. return;
  63737. }
  63738. var target = this.targetPosition;
  63739. var poleTarget = this.poleTargetPosition;
  63740. var mat1 = BoneIKController._tmpMats[0];
  63741. var mat2 = BoneIKController._tmpMats[1];
  63742. if (this.targetMesh) {
  63743. target.copyFrom(this.targetMesh.getAbsolutePosition());
  63744. }
  63745. if (this.poleTargetBone) {
  63746. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  63747. }
  63748. else if (this.poleTargetMesh) {
  63749. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  63750. }
  63751. var bonePos = BoneIKController._tmpVecs[0];
  63752. var zaxis = BoneIKController._tmpVecs[1];
  63753. var xaxis = BoneIKController._tmpVecs[2];
  63754. var yaxis = BoneIKController._tmpVecs[3];
  63755. var upAxis = BoneIKController._tmpVecs[4];
  63756. var _tmpQuat = BoneIKController._tmpQuat;
  63757. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  63758. poleTarget.subtractToRef(bonePos, upAxis);
  63759. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  63760. upAxis.y = 1;
  63761. }
  63762. else {
  63763. upAxis.normalize();
  63764. }
  63765. target.subtractToRef(bonePos, yaxis);
  63766. yaxis.normalize();
  63767. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  63768. zaxis.normalize();
  63769. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  63770. xaxis.normalize();
  63771. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  63772. var a = this._bone1Length;
  63773. var b = this._bone2Length;
  63774. var c = BABYLON.Vector3.Distance(bonePos, target);
  63775. if (this._maxReach > 0) {
  63776. c = Math.min(this._maxReach, c);
  63777. }
  63778. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  63779. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  63780. if (acosa > 1) {
  63781. acosa = 1;
  63782. }
  63783. if (acosb > 1) {
  63784. acosb = 1;
  63785. }
  63786. if (acosa < -1) {
  63787. acosa = -1;
  63788. }
  63789. if (acosb < -1) {
  63790. acosb = -1;
  63791. }
  63792. var angA = Math.acos(acosa);
  63793. var angB = Math.acos(acosb);
  63794. var angC = -angA - angB;
  63795. if (this._rightHandedSystem) {
  63796. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  63797. mat2.multiplyToRef(mat1, mat1);
  63798. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  63799. mat2.multiplyToRef(mat1, mat1);
  63800. }
  63801. else {
  63802. var _tmpVec = BoneIKController._tmpVecs[5];
  63803. _tmpVec.copyFrom(this._bendAxis);
  63804. _tmpVec.x *= -1;
  63805. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  63806. mat2.multiplyToRef(mat1, mat1);
  63807. }
  63808. if (this.poleAngle) {
  63809. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  63810. mat1.multiplyToRef(mat2, mat1);
  63811. }
  63812. if (this._bone1) {
  63813. if (this.slerpAmount < 1) {
  63814. if (!this._slerping) {
  63815. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  63816. }
  63817. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  63818. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  63819. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  63820. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  63821. this._slerping = true;
  63822. }
  63823. else {
  63824. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  63825. this._bone1Mat.copyFrom(mat1);
  63826. this._slerping = false;
  63827. }
  63828. }
  63829. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  63830. this._bone2Ang = angC;
  63831. };
  63832. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63833. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  63834. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  63835. return BoneIKController;
  63836. }());
  63837. BABYLON.BoneIKController = BoneIKController;
  63838. })(BABYLON || (BABYLON = {}));
  63839. //# sourceMappingURL=babylon.boneIKController.js.map
  63840. var BABYLON;
  63841. (function (BABYLON) {
  63842. var BoneLookController = /** @class */ (function () {
  63843. /**
  63844. * Create a BoneLookController
  63845. * @param mesh the mesh that the bone belongs to
  63846. * @param bone the bone that will be looking to the target
  63847. * @param target the target Vector3 to look at
  63848. * @param settings optional settings:
  63849. * - maxYaw: the maximum angle the bone will yaw to
  63850. * - minYaw: the minimum angle the bone will yaw to
  63851. * - maxPitch: the maximum angle the bone will pitch to
  63852. * - minPitch: the minimum angle the bone will yaw to
  63853. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  63854. * - upAxis: the up axis of the coordinate system
  63855. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  63856. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  63857. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  63858. * - adjustYaw: used to make an adjustment to the yaw of the bone
  63859. * - adjustPitch: used to make an adjustment to the pitch of the bone
  63860. * - adjustRoll: used to make an adjustment to the roll of the bone
  63861. **/
  63862. function BoneLookController(mesh, bone, target, options) {
  63863. /**
  63864. * The up axis of the coordinate system that is used when the bone is rotated.
  63865. */
  63866. this.upAxis = BABYLON.Vector3.Up();
  63867. /**
  63868. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  63869. */
  63870. this.upAxisSpace = BABYLON.Space.LOCAL;
  63871. /**
  63872. * Used to make an adjustment to the yaw of the bone.
  63873. */
  63874. this.adjustYaw = 0;
  63875. /**
  63876. * Used to make an adjustment to the pitch of the bone.
  63877. */
  63878. this.adjustPitch = 0;
  63879. /**
  63880. * Used to make an adjustment to the roll of the bone.
  63881. */
  63882. this.adjustRoll = 0;
  63883. /**
  63884. * 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).
  63885. */
  63886. this.slerpAmount = 1;
  63887. this._boneQuat = BABYLON.Quaternion.Identity();
  63888. this._slerping = false;
  63889. this._firstFrameSkipped = false;
  63890. this._fowardAxis = BABYLON.Vector3.Forward();
  63891. this.mesh = mesh;
  63892. this.bone = bone;
  63893. this.target = target;
  63894. if (options) {
  63895. if (options.adjustYaw) {
  63896. this.adjustYaw = options.adjustYaw;
  63897. }
  63898. if (options.adjustPitch) {
  63899. this.adjustPitch = options.adjustPitch;
  63900. }
  63901. if (options.adjustRoll) {
  63902. this.adjustRoll = options.adjustRoll;
  63903. }
  63904. if (options.maxYaw != null) {
  63905. this.maxYaw = options.maxYaw;
  63906. }
  63907. else {
  63908. this.maxYaw = Math.PI;
  63909. }
  63910. if (options.minYaw != null) {
  63911. this.minYaw = options.minYaw;
  63912. }
  63913. else {
  63914. this.minYaw = -Math.PI;
  63915. }
  63916. if (options.maxPitch != null) {
  63917. this.maxPitch = options.maxPitch;
  63918. }
  63919. else {
  63920. this.maxPitch = Math.PI;
  63921. }
  63922. if (options.minPitch != null) {
  63923. this.minPitch = options.minPitch;
  63924. }
  63925. else {
  63926. this.minPitch = -Math.PI;
  63927. }
  63928. if (options.slerpAmount != null) {
  63929. this.slerpAmount = options.slerpAmount;
  63930. }
  63931. if (options.upAxis != null) {
  63932. this.upAxis = options.upAxis;
  63933. }
  63934. if (options.upAxisSpace != null) {
  63935. this.upAxisSpace = options.upAxisSpace;
  63936. }
  63937. if (options.yawAxis != null || options.pitchAxis != null) {
  63938. var newYawAxis = BABYLON.Axis.Y;
  63939. var newPitchAxis = BABYLON.Axis.X;
  63940. if (options.yawAxis != null) {
  63941. newYawAxis = options.yawAxis.clone();
  63942. newYawAxis.normalize();
  63943. }
  63944. if (options.pitchAxis != null) {
  63945. newPitchAxis = options.pitchAxis.clone();
  63946. newPitchAxis.normalize();
  63947. }
  63948. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  63949. this._transformYawPitch = BABYLON.Matrix.Identity();
  63950. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  63951. this._transformYawPitchInv = this._transformYawPitch.clone();
  63952. this._transformYawPitch.invert();
  63953. }
  63954. }
  63955. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  63956. this.upAxisSpace = BABYLON.Space.LOCAL;
  63957. }
  63958. }
  63959. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  63960. /**
  63961. * Get/set the minimum yaw angle that the bone can look to.
  63962. */
  63963. get: function () {
  63964. return this._minYaw;
  63965. },
  63966. set: function (value) {
  63967. this._minYaw = value;
  63968. this._minYawSin = Math.sin(value);
  63969. this._minYawCos = Math.cos(value);
  63970. if (this._maxYaw != null) {
  63971. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  63972. this._yawRange = this._maxYaw - this._minYaw;
  63973. }
  63974. },
  63975. enumerable: true,
  63976. configurable: true
  63977. });
  63978. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  63979. /**
  63980. * Get/set the maximum yaw angle that the bone can look to.
  63981. */
  63982. get: function () {
  63983. return this._maxYaw;
  63984. },
  63985. set: function (value) {
  63986. this._maxYaw = value;
  63987. this._maxYawSin = Math.sin(value);
  63988. this._maxYawCos = Math.cos(value);
  63989. if (this._minYaw != null) {
  63990. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  63991. this._yawRange = this._maxYaw - this._minYaw;
  63992. }
  63993. },
  63994. enumerable: true,
  63995. configurable: true
  63996. });
  63997. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  63998. /**
  63999. * Get/set the minimum pitch angle that the bone can look to.
  64000. */
  64001. get: function () {
  64002. return this._minPitch;
  64003. },
  64004. set: function (value) {
  64005. this._minPitch = value;
  64006. this._minPitchTan = Math.tan(value);
  64007. },
  64008. enumerable: true,
  64009. configurable: true
  64010. });
  64011. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  64012. /**
  64013. * Get/set the maximum pitch angle that the bone can look to.
  64014. */
  64015. get: function () {
  64016. return this._maxPitch;
  64017. },
  64018. set: function (value) {
  64019. this._maxPitch = value;
  64020. this._maxPitchTan = Math.tan(value);
  64021. },
  64022. enumerable: true,
  64023. configurable: true
  64024. });
  64025. /**
  64026. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  64027. */
  64028. BoneLookController.prototype.update = function () {
  64029. //skip the first frame when slerping so that the mesh rotation is correct
  64030. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  64031. this._firstFrameSkipped = true;
  64032. return;
  64033. }
  64034. var bone = this.bone;
  64035. var bonePos = BoneLookController._tmpVecs[0];
  64036. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  64037. var target = this.target;
  64038. var _tmpMat1 = BoneLookController._tmpMats[0];
  64039. var _tmpMat2 = BoneLookController._tmpMats[1];
  64040. var mesh = this.mesh;
  64041. var parentBone = bone.getParent();
  64042. var upAxis = BoneLookController._tmpVecs[1];
  64043. upAxis.copyFrom(this.upAxis);
  64044. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  64045. if (this._transformYawPitch) {
  64046. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  64047. }
  64048. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  64049. }
  64050. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  64051. mesh.getDirectionToRef(upAxis, upAxis);
  64052. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  64053. upAxis.normalize();
  64054. }
  64055. }
  64056. var checkYaw = false;
  64057. var checkPitch = false;
  64058. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  64059. checkYaw = true;
  64060. }
  64061. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  64062. checkPitch = true;
  64063. }
  64064. if (checkYaw || checkPitch) {
  64065. var spaceMat = BoneLookController._tmpMats[2];
  64066. var spaceMatInv = BoneLookController._tmpMats[3];
  64067. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  64068. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  64069. }
  64070. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  64071. spaceMat.copyFrom(mesh.getWorldMatrix());
  64072. }
  64073. else {
  64074. var forwardAxis = BoneLookController._tmpVecs[2];
  64075. forwardAxis.copyFrom(this._fowardAxis);
  64076. if (this._transformYawPitch) {
  64077. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  64078. }
  64079. if (parentBone) {
  64080. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  64081. }
  64082. else {
  64083. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  64084. }
  64085. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  64086. rightAxis.normalize();
  64087. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  64088. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  64089. }
  64090. spaceMat.invertToRef(spaceMatInv);
  64091. var xzlen = null;
  64092. if (checkPitch) {
  64093. var localTarget = BoneLookController._tmpVecs[3];
  64094. target.subtractToRef(bonePos, localTarget);
  64095. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  64096. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  64097. var pitch = Math.atan2(localTarget.y, xzlen);
  64098. var newPitch = pitch;
  64099. if (pitch > this._maxPitch) {
  64100. localTarget.y = this._maxPitchTan * xzlen;
  64101. newPitch = this._maxPitch;
  64102. }
  64103. else if (pitch < this._minPitch) {
  64104. localTarget.y = this._minPitchTan * xzlen;
  64105. newPitch = this._minPitch;
  64106. }
  64107. if (pitch != newPitch) {
  64108. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  64109. localTarget.addInPlace(bonePos);
  64110. target = localTarget;
  64111. }
  64112. }
  64113. if (checkYaw) {
  64114. var localTarget = BoneLookController._tmpVecs[4];
  64115. target.subtractToRef(bonePos, localTarget);
  64116. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  64117. var yaw = Math.atan2(localTarget.x, localTarget.z);
  64118. var newYaw = yaw;
  64119. if (yaw > this._maxYaw || yaw < this._minYaw) {
  64120. if (xzlen == null) {
  64121. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  64122. }
  64123. if (this._yawRange > Math.PI) {
  64124. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  64125. localTarget.z = this._maxYawCos * xzlen;
  64126. localTarget.x = this._maxYawSin * xzlen;
  64127. newYaw = this._maxYaw;
  64128. }
  64129. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  64130. localTarget.z = this._minYawCos * xzlen;
  64131. localTarget.x = this._minYawSin * xzlen;
  64132. newYaw = this._minYaw;
  64133. }
  64134. }
  64135. else {
  64136. if (yaw > this._maxYaw) {
  64137. localTarget.z = this._maxYawCos * xzlen;
  64138. localTarget.x = this._maxYawSin * xzlen;
  64139. newYaw = this._maxYaw;
  64140. }
  64141. else if (yaw < this._minYaw) {
  64142. localTarget.z = this._minYawCos * xzlen;
  64143. localTarget.x = this._minYawSin * xzlen;
  64144. newYaw = this._minYaw;
  64145. }
  64146. }
  64147. }
  64148. if (this._slerping && this._yawRange > Math.PI) {
  64149. //are we going to be crossing into the min/max region?
  64150. var boneFwd = BoneLookController._tmpVecs[8];
  64151. boneFwd.copyFrom(BABYLON.Axis.Z);
  64152. if (this._transformYawPitch) {
  64153. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  64154. }
  64155. var boneRotMat = BoneLookController._tmpMats[4];
  64156. this._boneQuat.toRotationMatrix(boneRotMat);
  64157. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  64158. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  64159. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  64160. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  64161. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  64162. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  64163. if (angBtwTar > angBtwMidYaw) {
  64164. if (xzlen == null) {
  64165. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  64166. }
  64167. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  64168. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  64169. if (angBtwMin < angBtwMax) {
  64170. newYaw = boneYaw + Math.PI * .75;
  64171. localTarget.z = Math.cos(newYaw) * xzlen;
  64172. localTarget.x = Math.sin(newYaw) * xzlen;
  64173. }
  64174. else {
  64175. newYaw = boneYaw - Math.PI * .75;
  64176. localTarget.z = Math.cos(newYaw) * xzlen;
  64177. localTarget.x = Math.sin(newYaw) * xzlen;
  64178. }
  64179. }
  64180. }
  64181. if (yaw != newYaw) {
  64182. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  64183. localTarget.addInPlace(bonePos);
  64184. target = localTarget;
  64185. }
  64186. }
  64187. }
  64188. var zaxis = BoneLookController._tmpVecs[5];
  64189. var xaxis = BoneLookController._tmpVecs[6];
  64190. var yaxis = BoneLookController._tmpVecs[7];
  64191. var _tmpQuat = BoneLookController._tmpQuat;
  64192. target.subtractToRef(bonePos, zaxis);
  64193. zaxis.normalize();
  64194. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  64195. xaxis.normalize();
  64196. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  64197. yaxis.normalize();
  64198. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  64199. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  64200. return;
  64201. }
  64202. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  64203. return;
  64204. }
  64205. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  64206. return;
  64207. }
  64208. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  64209. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  64210. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  64211. }
  64212. if (this.slerpAmount < 1) {
  64213. if (!this._slerping) {
  64214. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  64215. }
  64216. if (this._transformYawPitch) {
  64217. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  64218. }
  64219. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  64220. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  64221. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  64222. this._slerping = true;
  64223. }
  64224. else {
  64225. if (this._transformYawPitch) {
  64226. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  64227. }
  64228. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  64229. this._slerping = false;
  64230. }
  64231. };
  64232. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  64233. var angDiff = ang2 - ang1;
  64234. angDiff %= Math.PI * 2;
  64235. if (angDiff > Math.PI) {
  64236. angDiff -= Math.PI * 2;
  64237. }
  64238. else if (angDiff < -Math.PI) {
  64239. angDiff += Math.PI * 2;
  64240. }
  64241. return angDiff;
  64242. };
  64243. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  64244. ang1 %= (2 * Math.PI);
  64245. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  64246. ang2 %= (2 * Math.PI);
  64247. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  64248. var ab = 0;
  64249. if (ang1 < ang2) {
  64250. ab = ang2 - ang1;
  64251. }
  64252. else {
  64253. ab = ang1 - ang2;
  64254. }
  64255. if (ab > Math.PI) {
  64256. ab = Math.PI * 2 - ab;
  64257. }
  64258. return ab;
  64259. };
  64260. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  64261. ang %= (2 * Math.PI);
  64262. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  64263. ang1 %= (2 * Math.PI);
  64264. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  64265. ang2 %= (2 * Math.PI);
  64266. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  64267. if (ang1 < ang2) {
  64268. if (ang > ang1 && ang < ang2) {
  64269. return true;
  64270. }
  64271. }
  64272. else {
  64273. if (ang > ang2 && ang < ang1) {
  64274. return true;
  64275. }
  64276. }
  64277. return false;
  64278. };
  64279. 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()];
  64280. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  64281. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  64282. return BoneLookController;
  64283. }());
  64284. BABYLON.BoneLookController = BoneLookController;
  64285. })(BABYLON || (BABYLON = {}));
  64286. //# sourceMappingURL=babylon.boneLookController.js.map
  64287. var BABYLON;
  64288. (function (BABYLON) {
  64289. var Skeleton = /** @class */ (function () {
  64290. function Skeleton(name, id, scene) {
  64291. this.name = name;
  64292. this.id = id;
  64293. this.bones = new Array();
  64294. this.needInitialSkinMatrix = false;
  64295. this._isDirty = true;
  64296. this._meshesWithPoseMatrix = new Array();
  64297. this._identity = BABYLON.Matrix.Identity();
  64298. this._ranges = {};
  64299. this._lastAbsoluteTransformsUpdateId = -1;
  64300. // Events
  64301. /**
  64302. * An event triggered before computing the skeleton's matrices
  64303. * @type {BABYLON.Observable}
  64304. */
  64305. this.onBeforeComputeObservable = new BABYLON.Observable();
  64306. this.bones = [];
  64307. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64308. scene.skeletons.push(this);
  64309. //make sure it will recalculate the matrix next time prepare is called.
  64310. this._isDirty = true;
  64311. }
  64312. // Members
  64313. Skeleton.prototype.getTransformMatrices = function (mesh) {
  64314. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  64315. return mesh._bonesTransformMatrices;
  64316. }
  64317. if (!this._transformMatrices) {
  64318. this.prepare();
  64319. }
  64320. return this._transformMatrices;
  64321. };
  64322. Skeleton.prototype.getScene = function () {
  64323. return this._scene;
  64324. };
  64325. // Methods
  64326. /**
  64327. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  64328. */
  64329. Skeleton.prototype.toString = function (fullDetails) {
  64330. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  64331. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  64332. if (fullDetails) {
  64333. ret += ", Ranges: {";
  64334. var first = true;
  64335. for (var name_1 in this._ranges) {
  64336. if (first) {
  64337. ret += ", ";
  64338. first = false;
  64339. }
  64340. ret += name_1;
  64341. }
  64342. ret += "}";
  64343. }
  64344. return ret;
  64345. };
  64346. /**
  64347. * Get bone's index searching by name
  64348. * @param {string} name is bone's name to search for
  64349. * @return {number} Indice of the bone. Returns -1 if not found
  64350. */
  64351. Skeleton.prototype.getBoneIndexByName = function (name) {
  64352. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  64353. if (this.bones[boneIndex].name === name) {
  64354. return boneIndex;
  64355. }
  64356. }
  64357. return -1;
  64358. };
  64359. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  64360. // check name not already in use
  64361. if (!this._ranges[name]) {
  64362. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  64363. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  64364. if (this.bones[i].animations[0]) {
  64365. this.bones[i].animations[0].createRange(name, from, to);
  64366. }
  64367. }
  64368. }
  64369. };
  64370. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  64371. if (deleteFrames === void 0) { deleteFrames = true; }
  64372. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  64373. if (this.bones[i].animations[0]) {
  64374. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  64375. }
  64376. }
  64377. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  64378. };
  64379. Skeleton.prototype.getAnimationRange = function (name) {
  64380. return this._ranges[name];
  64381. };
  64382. /**
  64383. * Returns as an Array, all AnimationRanges defined on this skeleton
  64384. */
  64385. Skeleton.prototype.getAnimationRanges = function () {
  64386. var animationRanges = [];
  64387. var name;
  64388. var i = 0;
  64389. for (name in this._ranges) {
  64390. animationRanges[i] = this._ranges[name];
  64391. i++;
  64392. }
  64393. return animationRanges;
  64394. };
  64395. /**
  64396. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  64397. */
  64398. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  64399. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  64400. if (this._ranges[name] || !source.getAnimationRange(name)) {
  64401. return false;
  64402. }
  64403. var ret = true;
  64404. var frameOffset = this._getHighestAnimationFrame() + 1;
  64405. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  64406. var boneDict = {};
  64407. var sourceBones = source.bones;
  64408. var nBones;
  64409. var i;
  64410. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  64411. boneDict[sourceBones[i].name] = sourceBones[i];
  64412. }
  64413. if (this.bones.length !== sourceBones.length) {
  64414. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  64415. ret = false;
  64416. }
  64417. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  64418. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  64419. var boneName = this.bones[i].name;
  64420. var sourceBone = boneDict[boneName];
  64421. if (sourceBone) {
  64422. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  64423. }
  64424. else {
  64425. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  64426. ret = false;
  64427. }
  64428. }
  64429. // do not call createAnimationRange(), since it also is done to bones, which was already done
  64430. var range = source.getAnimationRange(name);
  64431. if (range) {
  64432. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  64433. }
  64434. return ret;
  64435. };
  64436. Skeleton.prototype.returnToRest = function () {
  64437. for (var index = 0; index < this.bones.length; index++) {
  64438. this.bones[index].returnToRest();
  64439. }
  64440. };
  64441. Skeleton.prototype._getHighestAnimationFrame = function () {
  64442. var ret = 0;
  64443. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  64444. if (this.bones[i].animations[0]) {
  64445. var highest = this.bones[i].animations[0].getHighestFrame();
  64446. if (ret < highest) {
  64447. ret = highest;
  64448. }
  64449. }
  64450. }
  64451. return ret;
  64452. };
  64453. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  64454. var range = this.getAnimationRange(name);
  64455. if (!range) {
  64456. return null;
  64457. }
  64458. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  64459. };
  64460. Skeleton.prototype._markAsDirty = function () {
  64461. this._isDirty = true;
  64462. };
  64463. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  64464. this._meshesWithPoseMatrix.push(mesh);
  64465. };
  64466. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  64467. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  64468. if (index > -1) {
  64469. this._meshesWithPoseMatrix.splice(index, 1);
  64470. }
  64471. };
  64472. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  64473. this.onBeforeComputeObservable.notifyObservers(this);
  64474. for (var index = 0; index < this.bones.length; index++) {
  64475. var bone = this.bones[index];
  64476. var parentBone = bone.getParent();
  64477. if (parentBone) {
  64478. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  64479. }
  64480. else {
  64481. if (initialSkinMatrix) {
  64482. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  64483. }
  64484. else {
  64485. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  64486. }
  64487. }
  64488. if (bone._index !== -1) {
  64489. var mappedIndex = bone._index === null ? index : bone._index;
  64490. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  64491. }
  64492. }
  64493. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  64494. };
  64495. Skeleton.prototype.prepare = function () {
  64496. if (!this._isDirty) {
  64497. return;
  64498. }
  64499. if (this.needInitialSkinMatrix) {
  64500. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  64501. var mesh = this._meshesWithPoseMatrix[index];
  64502. var poseMatrix = mesh.getPoseMatrix();
  64503. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  64504. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  64505. }
  64506. if (this._synchronizedWithMesh !== mesh) {
  64507. this._synchronizedWithMesh = mesh;
  64508. // Prepare bones
  64509. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  64510. var bone = this.bones[boneIndex];
  64511. if (!bone.getParent()) {
  64512. var matrix = bone.getBaseMatrix();
  64513. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  64514. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  64515. }
  64516. }
  64517. }
  64518. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  64519. }
  64520. }
  64521. else {
  64522. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  64523. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  64524. }
  64525. this._computeTransformMatrices(this._transformMatrices, null);
  64526. }
  64527. this._isDirty = false;
  64528. this._scene._activeBones.addCount(this.bones.length, false);
  64529. };
  64530. Skeleton.prototype.getAnimatables = function () {
  64531. if (!this._animatables || this._animatables.length !== this.bones.length) {
  64532. this._animatables = [];
  64533. for (var index = 0; index < this.bones.length; index++) {
  64534. this._animatables.push(this.bones[index]);
  64535. }
  64536. }
  64537. return this._animatables;
  64538. };
  64539. Skeleton.prototype.clone = function (name, id) {
  64540. var result = new Skeleton(name, id || name, this._scene);
  64541. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  64542. for (var index = 0; index < this.bones.length; index++) {
  64543. var source = this.bones[index];
  64544. var parentBone = null;
  64545. var parent_1 = source.getParent();
  64546. if (parent_1) {
  64547. var parentIndex = this.bones.indexOf(parent_1);
  64548. parentBone = result.bones[parentIndex];
  64549. }
  64550. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  64551. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  64552. }
  64553. if (this._ranges) {
  64554. result._ranges = {};
  64555. for (var rangeName in this._ranges) {
  64556. var range = this._ranges[rangeName];
  64557. if (range) {
  64558. result._ranges[rangeName] = range.clone();
  64559. }
  64560. }
  64561. }
  64562. this._isDirty = true;
  64563. return result;
  64564. };
  64565. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  64566. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  64567. this.bones.forEach(function (bone) {
  64568. bone.animations.forEach(function (animation) {
  64569. animation.enableBlending = true;
  64570. animation.blendingSpeed = blendingSpeed;
  64571. });
  64572. });
  64573. };
  64574. Skeleton.prototype.dispose = function () {
  64575. this._meshesWithPoseMatrix = [];
  64576. // Animations
  64577. this.getScene().stopAnimation(this);
  64578. // Remove from scene
  64579. this.getScene().removeSkeleton(this);
  64580. };
  64581. Skeleton.prototype.serialize = function () {
  64582. var serializationObject = {};
  64583. serializationObject.name = this.name;
  64584. serializationObject.id = this.id;
  64585. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  64586. serializationObject.bones = [];
  64587. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  64588. for (var index = 0; index < this.bones.length; index++) {
  64589. var bone = this.bones[index];
  64590. var parent_2 = bone.getParent();
  64591. var serializedBone = {
  64592. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  64593. name: bone.name,
  64594. matrix: bone.getBaseMatrix().toArray(),
  64595. rest: bone.getRestPose().toArray()
  64596. };
  64597. serializationObject.bones.push(serializedBone);
  64598. if (bone.length) {
  64599. serializedBone.length = bone.length;
  64600. }
  64601. if (bone.animations && bone.animations.length > 0) {
  64602. serializedBone.animation = bone.animations[0].serialize();
  64603. }
  64604. serializationObject.ranges = [];
  64605. for (var name in this._ranges) {
  64606. var source = this._ranges[name];
  64607. if (!source) {
  64608. continue;
  64609. }
  64610. var range = {};
  64611. range.name = name;
  64612. range.from = source.from;
  64613. range.to = source.to;
  64614. serializationObject.ranges.push(range);
  64615. }
  64616. }
  64617. return serializationObject;
  64618. };
  64619. Skeleton.Parse = function (parsedSkeleton, scene) {
  64620. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  64621. if (parsedSkeleton.dimensionsAtRest) {
  64622. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  64623. }
  64624. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  64625. var index;
  64626. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  64627. var parsedBone = parsedSkeleton.bones[index];
  64628. var parentBone = null;
  64629. if (parsedBone.parentBoneIndex > -1) {
  64630. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  64631. }
  64632. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  64633. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  64634. if (parsedBone.length) {
  64635. bone.length = parsedBone.length;
  64636. }
  64637. if (parsedBone.animation) {
  64638. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  64639. }
  64640. }
  64641. // placed after bones, so createAnimationRange can cascade down
  64642. if (parsedSkeleton.ranges) {
  64643. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  64644. var data = parsedSkeleton.ranges[index];
  64645. skeleton.createAnimationRange(data.name, data.from, data.to);
  64646. }
  64647. }
  64648. return skeleton;
  64649. };
  64650. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  64651. if (forceUpdate === void 0) { forceUpdate = false; }
  64652. var renderId = this._scene.getRenderId();
  64653. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  64654. this.bones[0].computeAbsoluteTransforms();
  64655. this._lastAbsoluteTransformsUpdateId = renderId;
  64656. }
  64657. };
  64658. Skeleton.prototype.getPoseMatrix = function () {
  64659. var poseMatrix = null;
  64660. if (this._meshesWithPoseMatrix.length > 0) {
  64661. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  64662. }
  64663. return poseMatrix;
  64664. };
  64665. Skeleton.prototype.sortBones = function () {
  64666. var bones = new Array();
  64667. var visited = new Array(this.bones.length);
  64668. for (var index = 0; index < this.bones.length; index++) {
  64669. this._sortBones(index, bones, visited);
  64670. }
  64671. this.bones = bones;
  64672. };
  64673. Skeleton.prototype._sortBones = function (index, bones, visited) {
  64674. if (visited[index]) {
  64675. return;
  64676. }
  64677. visited[index] = true;
  64678. var bone = this.bones[index];
  64679. if (bone._index === undefined) {
  64680. bone._index = index;
  64681. }
  64682. var parentBone = bone.getParent();
  64683. if (parentBone) {
  64684. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  64685. }
  64686. bones.push(bone);
  64687. };
  64688. return Skeleton;
  64689. }());
  64690. BABYLON.Skeleton = Skeleton;
  64691. })(BABYLON || (BABYLON = {}));
  64692. //# sourceMappingURL=babylon.skeleton.js.map
  64693. var BABYLON;
  64694. (function (BABYLON) {
  64695. var SphericalPolynomial = /** @class */ (function () {
  64696. function SphericalPolynomial() {
  64697. this.x = BABYLON.Vector3.Zero();
  64698. this.y = BABYLON.Vector3.Zero();
  64699. this.z = BABYLON.Vector3.Zero();
  64700. this.xx = BABYLON.Vector3.Zero();
  64701. this.yy = BABYLON.Vector3.Zero();
  64702. this.zz = BABYLON.Vector3.Zero();
  64703. this.xy = BABYLON.Vector3.Zero();
  64704. this.yz = BABYLON.Vector3.Zero();
  64705. this.zx = BABYLON.Vector3.Zero();
  64706. }
  64707. SphericalPolynomial.prototype.addAmbient = function (color) {
  64708. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  64709. this.xx = this.xx.add(colorVector);
  64710. this.yy = this.yy.add(colorVector);
  64711. this.zz = this.zz.add(colorVector);
  64712. };
  64713. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  64714. var result = new SphericalPolynomial();
  64715. result.x = harmonics.L11.scale(1.02333);
  64716. result.y = harmonics.L1_1.scale(1.02333);
  64717. result.z = harmonics.L10.scale(1.02333);
  64718. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  64719. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  64720. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  64721. result.yz = harmonics.L2_1.scale(0.858086);
  64722. result.zx = harmonics.L21.scale(0.858086);
  64723. result.xy = harmonics.L2_2.scale(0.858086);
  64724. result.scale(1.0 / Math.PI);
  64725. return result;
  64726. };
  64727. SphericalPolynomial.prototype.scale = function (scale) {
  64728. this.x = this.x.scale(scale);
  64729. this.y = this.y.scale(scale);
  64730. this.z = this.z.scale(scale);
  64731. this.xx = this.xx.scale(scale);
  64732. this.yy = this.yy.scale(scale);
  64733. this.zz = this.zz.scale(scale);
  64734. this.yz = this.yz.scale(scale);
  64735. this.zx = this.zx.scale(scale);
  64736. this.xy = this.xy.scale(scale);
  64737. };
  64738. return SphericalPolynomial;
  64739. }());
  64740. BABYLON.SphericalPolynomial = SphericalPolynomial;
  64741. var SphericalHarmonics = /** @class */ (function () {
  64742. function SphericalHarmonics() {
  64743. this.L00 = BABYLON.Vector3.Zero();
  64744. this.L1_1 = BABYLON.Vector3.Zero();
  64745. this.L10 = BABYLON.Vector3.Zero();
  64746. this.L11 = BABYLON.Vector3.Zero();
  64747. this.L2_2 = BABYLON.Vector3.Zero();
  64748. this.L2_1 = BABYLON.Vector3.Zero();
  64749. this.L20 = BABYLON.Vector3.Zero();
  64750. this.L21 = BABYLON.Vector3.Zero();
  64751. this.L22 = BABYLON.Vector3.Zero();
  64752. }
  64753. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  64754. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  64755. var c = colorVector.scale(deltaSolidAngle);
  64756. this.L00 = this.L00.add(c.scale(0.282095));
  64757. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  64758. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  64759. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  64760. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  64761. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  64762. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  64763. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  64764. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  64765. };
  64766. SphericalHarmonics.prototype.scale = function (scale) {
  64767. this.L00 = this.L00.scale(scale);
  64768. this.L1_1 = this.L1_1.scale(scale);
  64769. this.L10 = this.L10.scale(scale);
  64770. this.L11 = this.L11.scale(scale);
  64771. this.L2_2 = this.L2_2.scale(scale);
  64772. this.L2_1 = this.L2_1.scale(scale);
  64773. this.L20 = this.L20.scale(scale);
  64774. this.L21 = this.L21.scale(scale);
  64775. this.L22 = this.L22.scale(scale);
  64776. };
  64777. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  64778. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  64779. //
  64780. // E_lm = A_l * L_lm
  64781. //
  64782. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  64783. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  64784. // the scaling factors are given in equation 9.
  64785. // Constant (Band 0)
  64786. this.L00 = this.L00.scale(3.141593);
  64787. // Linear (Band 1)
  64788. this.L1_1 = this.L1_1.scale(2.094395);
  64789. this.L10 = this.L10.scale(2.094395);
  64790. this.L11 = this.L11.scale(2.094395);
  64791. // Quadratic (Band 2)
  64792. this.L2_2 = this.L2_2.scale(0.785398);
  64793. this.L2_1 = this.L2_1.scale(0.785398);
  64794. this.L20 = this.L20.scale(0.785398);
  64795. this.L21 = this.L21.scale(0.785398);
  64796. this.L22 = this.L22.scale(0.785398);
  64797. };
  64798. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  64799. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  64800. // L = (1/pi) * E * rho
  64801. //
  64802. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  64803. this.scale(1.0 / Math.PI);
  64804. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  64805. // (The pixel shader must apply albedo after texture fetches, etc).
  64806. };
  64807. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  64808. var result = new SphericalHarmonics();
  64809. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  64810. result.L1_1 = polynomial.y.scale(0.977204);
  64811. result.L10 = polynomial.z.scale(0.977204);
  64812. result.L11 = polynomial.x.scale(0.977204);
  64813. result.L2_2 = polynomial.xy.scale(1.16538);
  64814. result.L2_1 = polynomial.yz.scale(1.16538);
  64815. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  64816. result.L21 = polynomial.zx.scale(1.16538);
  64817. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  64818. result.scale(Math.PI);
  64819. return result;
  64820. };
  64821. return SphericalHarmonics;
  64822. }());
  64823. BABYLON.SphericalHarmonics = SphericalHarmonics;
  64824. })(BABYLON || (BABYLON = {}));
  64825. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  64826. var BABYLON;
  64827. (function (BABYLON) {
  64828. var Internals;
  64829. (function (Internals) {
  64830. var FileFaceOrientation = /** @class */ (function () {
  64831. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  64832. this.name = name;
  64833. this.worldAxisForNormal = worldAxisForNormal;
  64834. this.worldAxisForFileX = worldAxisForFileX;
  64835. this.worldAxisForFileY = worldAxisForFileY;
  64836. }
  64837. return FileFaceOrientation;
  64838. }());
  64839. ;
  64840. /**
  64841. * Helper class dealing with the extraction of spherical polynomial dataArray
  64842. * from a cube map.
  64843. */
  64844. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  64845. function CubeMapToSphericalPolynomialTools() {
  64846. }
  64847. /**
  64848. * Converts a texture to the according Spherical Polynomial data.
  64849. * This extracts the first 3 orders only as they are the only one used in the lighting.
  64850. *
  64851. * @param texture The texture to extract the information from.
  64852. * @return The Spherical Polynomial data.
  64853. */
  64854. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  64855. if (!texture.isCube) {
  64856. // Only supports cube Textures currently.
  64857. return null;
  64858. }
  64859. var size = texture.getSize().width;
  64860. var right = texture.readPixels(0);
  64861. var left = texture.readPixels(1);
  64862. var up;
  64863. var down;
  64864. if (texture.isRenderTarget) {
  64865. up = texture.readPixels(3);
  64866. down = texture.readPixels(2);
  64867. }
  64868. else {
  64869. up = texture.readPixels(2);
  64870. down = texture.readPixels(3);
  64871. }
  64872. var front = texture.readPixels(4);
  64873. var back = texture.readPixels(5);
  64874. var gammaSpace = texture.gammaSpace;
  64875. // Always read as RGBA.
  64876. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  64877. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  64878. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  64879. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  64880. }
  64881. var cubeInfo = {
  64882. size: size,
  64883. right: right,
  64884. left: left,
  64885. up: up,
  64886. down: down,
  64887. front: front,
  64888. back: back,
  64889. format: format,
  64890. type: type,
  64891. gammaSpace: gammaSpace,
  64892. };
  64893. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  64894. };
  64895. /**
  64896. * Converts a cubemap to the according Spherical Polynomial data.
  64897. * This extracts the first 3 orders only as they are the only one used in the lighting.
  64898. *
  64899. * @param cubeInfo The Cube map to extract the information from.
  64900. * @return The Spherical Polynomial data.
  64901. */
  64902. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  64903. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  64904. var totalSolidAngle = 0.0;
  64905. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  64906. var du = 2.0 / cubeInfo.size;
  64907. var dv = du;
  64908. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  64909. var minUV = du * 0.5 - 1.0;
  64910. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  64911. var fileFace = this.FileFaces[faceIndex];
  64912. var dataArray = cubeInfo[fileFace.name];
  64913. var v = minUV;
  64914. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  64915. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  64916. // Because SP is still linear, so summation is fine in that basis.
  64917. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  64918. for (var y = 0; y < cubeInfo.size; y++) {
  64919. var u = minUV;
  64920. for (var x = 0; x < cubeInfo.size; x++) {
  64921. // World direction (not normalised)
  64922. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  64923. worldDirection.normalize();
  64924. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  64925. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  64926. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  64927. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  64928. // Handle Integer types.
  64929. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  64930. r /= 255;
  64931. g /= 255;
  64932. b /= 255;
  64933. }
  64934. // Handle Gamma space textures.
  64935. if (cubeInfo.gammaSpace) {
  64936. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  64937. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  64938. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  64939. }
  64940. var color = new BABYLON.Color3(r, g, b);
  64941. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  64942. totalSolidAngle += deltaSolidAngle;
  64943. u += du;
  64944. }
  64945. v += dv;
  64946. }
  64947. }
  64948. // Solid angle for entire sphere is 4*pi
  64949. var sphereSolidAngle = 4.0 * Math.PI;
  64950. // Adjust the solid angle to allow for how many faces we processed.
  64951. var facesProcessed = 6.0;
  64952. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  64953. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  64954. // This is needed because the numerical integration over the cube uses a
  64955. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  64956. // and also to compensate for accumulative error due to float precision in the summation.
  64957. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  64958. sphericalHarmonics.scale(correctionFactor);
  64959. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  64960. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  64961. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  64962. };
  64963. CubeMapToSphericalPolynomialTools.FileFaces = [
  64964. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  64965. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  64966. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  64967. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  64968. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  64969. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  64970. ];
  64971. return CubeMapToSphericalPolynomialTools;
  64972. }());
  64973. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  64974. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  64975. })(BABYLON || (BABYLON = {}));
  64976. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  64977. var BABYLON;
  64978. (function (BABYLON) {
  64979. var Internals;
  64980. (function (Internals) {
  64981. /**
  64982. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  64983. */
  64984. var PanoramaToCubeMapTools = /** @class */ (function () {
  64985. function PanoramaToCubeMapTools() {
  64986. }
  64987. /**
  64988. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  64989. *
  64990. * @param float32Array The source data.
  64991. * @param inputWidth The width of the input panorama.
  64992. * @param inputhHeight The height of the input panorama.
  64993. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  64994. * @return The cubemap data
  64995. */
  64996. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  64997. if (!float32Array) {
  64998. throw "ConvertPanoramaToCubemap: input cannot be null";
  64999. }
  65000. if (float32Array.length != inputWidth * inputHeight * 3) {
  65001. throw "ConvertPanoramaToCubemap: input size is wrong";
  65002. }
  65003. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  65004. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  65005. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  65006. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  65007. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  65008. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  65009. return {
  65010. front: textureFront,
  65011. back: textureBack,
  65012. left: textureLeft,
  65013. right: textureRight,
  65014. up: textureUp,
  65015. down: textureDown,
  65016. size: size,
  65017. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  65018. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  65019. gammaSpace: false,
  65020. };
  65021. };
  65022. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  65023. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  65024. var textureArray = new Float32Array(buffer);
  65025. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  65026. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  65027. var dy = 1 / texSize;
  65028. var fy = 0;
  65029. for (var y = 0; y < texSize; y++) {
  65030. var xv1 = faceData[0];
  65031. var xv2 = faceData[2];
  65032. for (var x = 0; x < texSize; x++) {
  65033. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  65034. v.normalize();
  65035. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  65036. // 3 channels per pixels
  65037. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  65038. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  65039. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  65040. xv1 = xv1.add(rotDX1);
  65041. xv2 = xv2.add(rotDX2);
  65042. }
  65043. fy += dy;
  65044. }
  65045. return textureArray;
  65046. };
  65047. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  65048. var theta = Math.atan2(vDir.z, vDir.x);
  65049. var phi = Math.acos(vDir.y);
  65050. while (theta < -Math.PI)
  65051. theta += 2 * Math.PI;
  65052. while (theta > Math.PI)
  65053. theta -= 2 * Math.PI;
  65054. var dx = theta / Math.PI;
  65055. var dy = phi / Math.PI;
  65056. // recenter.
  65057. dx = dx * 0.5 + 0.5;
  65058. var px = Math.round(dx * inputWidth);
  65059. if (px < 0)
  65060. px = 0;
  65061. else if (px >= inputWidth)
  65062. px = inputWidth - 1;
  65063. var py = Math.round(dy * inputHeight);
  65064. if (py < 0)
  65065. py = 0;
  65066. else if (py >= inputHeight)
  65067. py = inputHeight - 1;
  65068. var inputY = (inputHeight - py - 1);
  65069. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  65070. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  65071. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  65072. return {
  65073. r: r,
  65074. g: g,
  65075. b: b
  65076. };
  65077. };
  65078. PanoramaToCubeMapTools.FACE_FRONT = [
  65079. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  65080. new BABYLON.Vector3(1.0, -1.0, -1.0),
  65081. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  65082. new BABYLON.Vector3(1.0, 1.0, -1.0)
  65083. ];
  65084. PanoramaToCubeMapTools.FACE_BACK = [
  65085. new BABYLON.Vector3(1.0, -1.0, 1.0),
  65086. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  65087. new BABYLON.Vector3(1.0, 1.0, 1.0),
  65088. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  65089. ];
  65090. PanoramaToCubeMapTools.FACE_RIGHT = [
  65091. new BABYLON.Vector3(1.0, -1.0, -1.0),
  65092. new BABYLON.Vector3(1.0, -1.0, 1.0),
  65093. new BABYLON.Vector3(1.0, 1.0, -1.0),
  65094. new BABYLON.Vector3(1.0, 1.0, 1.0)
  65095. ];
  65096. PanoramaToCubeMapTools.FACE_LEFT = [
  65097. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  65098. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  65099. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  65100. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  65101. ];
  65102. PanoramaToCubeMapTools.FACE_DOWN = [
  65103. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  65104. new BABYLON.Vector3(1.0, 1.0, -1.0),
  65105. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  65106. new BABYLON.Vector3(1.0, 1.0, 1.0)
  65107. ];
  65108. PanoramaToCubeMapTools.FACE_UP = [
  65109. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  65110. new BABYLON.Vector3(1.0, -1.0, 1.0),
  65111. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  65112. new BABYLON.Vector3(1.0, -1.0, -1.0)
  65113. ];
  65114. return PanoramaToCubeMapTools;
  65115. }());
  65116. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  65117. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  65118. })(BABYLON || (BABYLON = {}));
  65119. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  65120. var BABYLON;
  65121. (function (BABYLON) {
  65122. var Internals;
  65123. (function (Internals) {
  65124. ;
  65125. /**
  65126. * This groups tools to convert HDR texture to native colors array.
  65127. */
  65128. var HDRTools = /** @class */ (function () {
  65129. function HDRTools() {
  65130. }
  65131. HDRTools.Ldexp = function (mantissa, exponent) {
  65132. if (exponent > 1023) {
  65133. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  65134. }
  65135. if (exponent < -1074) {
  65136. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  65137. }
  65138. return mantissa * Math.pow(2, exponent);
  65139. };
  65140. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  65141. if (exponent > 0) {
  65142. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  65143. float32array[index + 0] = red * exponent;
  65144. float32array[index + 1] = green * exponent;
  65145. float32array[index + 2] = blue * exponent;
  65146. }
  65147. else {
  65148. float32array[index + 0] = 0;
  65149. float32array[index + 1] = 0;
  65150. float32array[index + 2] = 0;
  65151. }
  65152. };
  65153. HDRTools.readStringLine = function (uint8array, startIndex) {
  65154. var line = "";
  65155. var character = "";
  65156. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  65157. character = String.fromCharCode(uint8array[i]);
  65158. if (character == "\n") {
  65159. break;
  65160. }
  65161. line += character;
  65162. }
  65163. return line;
  65164. };
  65165. /**
  65166. * Reads header information from an RGBE texture stored in a native array.
  65167. * More information on this format are available here:
  65168. * https://en.wikipedia.org/wiki/RGBE_image_format
  65169. *
  65170. * @param uint8array The binary file stored in native array.
  65171. * @return The header information.
  65172. */
  65173. HDRTools.RGBE_ReadHeader = function (uint8array) {
  65174. var height = 0;
  65175. var width = 0;
  65176. var line = this.readStringLine(uint8array, 0);
  65177. if (line[0] != '#' || line[1] != '?') {
  65178. throw "Bad HDR Format.";
  65179. }
  65180. var endOfHeader = false;
  65181. var findFormat = false;
  65182. var lineIndex = 0;
  65183. do {
  65184. lineIndex += (line.length + 1);
  65185. line = this.readStringLine(uint8array, lineIndex);
  65186. if (line == "FORMAT=32-bit_rle_rgbe") {
  65187. findFormat = true;
  65188. }
  65189. else if (line.length == 0) {
  65190. endOfHeader = true;
  65191. }
  65192. } while (!endOfHeader);
  65193. if (!findFormat) {
  65194. throw "HDR Bad header format, unsupported FORMAT";
  65195. }
  65196. lineIndex += (line.length + 1);
  65197. line = this.readStringLine(uint8array, lineIndex);
  65198. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  65199. var match = sizeRegexp.exec(line);
  65200. // TODO. Support +Y and -X if needed.
  65201. if (!match || match.length < 3) {
  65202. throw "HDR Bad header format, no size";
  65203. }
  65204. width = parseInt(match[2]);
  65205. height = parseInt(match[1]);
  65206. if (width < 8 || width > 0x7fff) {
  65207. throw "HDR Bad header format, unsupported size";
  65208. }
  65209. lineIndex += (line.length + 1);
  65210. return {
  65211. height: height,
  65212. width: width,
  65213. dataPosition: lineIndex
  65214. };
  65215. };
  65216. /**
  65217. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  65218. * This RGBE texture needs to store the information as a panorama.
  65219. *
  65220. * More information on this format are available here:
  65221. * https://en.wikipedia.org/wiki/RGBE_image_format
  65222. *
  65223. * @param buffer The binary file stored in an array buffer.
  65224. * @param size The expected size of the extracted cubemap.
  65225. * @return The Cube Map information.
  65226. */
  65227. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  65228. var uint8array = new Uint8Array(buffer);
  65229. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  65230. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  65231. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  65232. return cubeMapData;
  65233. };
  65234. /**
  65235. * Returns the pixels data extracted from an RGBE texture.
  65236. * This pixels will be stored left to right up to down in the R G B order in one array.
  65237. *
  65238. * More information on this format are available here:
  65239. * https://en.wikipedia.org/wiki/RGBE_image_format
  65240. *
  65241. * @param uint8array The binary file stored in an array buffer.
  65242. * @param hdrInfo The header information of the file.
  65243. * @return The pixels data in RGB right to left up to down order.
  65244. */
  65245. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  65246. // Keep for multi format supports.
  65247. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  65248. };
  65249. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  65250. var num_scanlines = hdrInfo.height;
  65251. var scanline_width = hdrInfo.width;
  65252. var a, b, c, d, count;
  65253. var dataIndex = hdrInfo.dataPosition;
  65254. var index = 0, endIndex = 0, i = 0;
  65255. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  65256. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  65257. // 3 channels of 4 bytes per pixel in float.
  65258. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  65259. var resultArray = new Float32Array(resultBuffer);
  65260. // read in each successive scanline
  65261. while (num_scanlines > 0) {
  65262. a = uint8array[dataIndex++];
  65263. b = uint8array[dataIndex++];
  65264. c = uint8array[dataIndex++];
  65265. d = uint8array[dataIndex++];
  65266. if (a != 2 || b != 2 || (c & 0x80)) {
  65267. // this file is not run length encoded
  65268. throw "HDR Bad header format, not RLE";
  65269. }
  65270. if (((c << 8) | d) != scanline_width) {
  65271. throw "HDR Bad header format, wrong scan line width";
  65272. }
  65273. index = 0;
  65274. // read each of the four channels for the scanline into the buffer
  65275. for (i = 0; i < 4; i++) {
  65276. endIndex = (i + 1) * scanline_width;
  65277. while (index < endIndex) {
  65278. a = uint8array[dataIndex++];
  65279. b = uint8array[dataIndex++];
  65280. if (a > 128) {
  65281. // a run of the same value
  65282. count = a - 128;
  65283. if ((count == 0) || (count > endIndex - index)) {
  65284. throw "HDR Bad Format, bad scanline data (run)";
  65285. }
  65286. while (count-- > 0) {
  65287. scanLineArray[index++] = b;
  65288. }
  65289. }
  65290. else {
  65291. // a non-run
  65292. count = a;
  65293. if ((count == 0) || (count > endIndex - index)) {
  65294. throw "HDR Bad Format, bad scanline data (non-run)";
  65295. }
  65296. scanLineArray[index++] = b;
  65297. if (--count > 0) {
  65298. for (var j = 0; j < count; j++) {
  65299. scanLineArray[index++] = uint8array[dataIndex++];
  65300. }
  65301. }
  65302. }
  65303. }
  65304. }
  65305. // now convert data from buffer into floats
  65306. for (i = 0; i < scanline_width; i++) {
  65307. a = scanLineArray[i];
  65308. b = scanLineArray[i + scanline_width];
  65309. c = scanLineArray[i + 2 * scanline_width];
  65310. d = scanLineArray[i + 3 * scanline_width];
  65311. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  65312. }
  65313. num_scanlines--;
  65314. }
  65315. return resultArray;
  65316. };
  65317. return HDRTools;
  65318. }());
  65319. Internals.HDRTools = HDRTools;
  65320. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  65321. })(BABYLON || (BABYLON = {}));
  65322. //# sourceMappingURL=babylon.hdr.js.map
  65323. var BABYLON;
  65324. (function (BABYLON) {
  65325. /**
  65326. * This represents a texture coming from an HDR input.
  65327. *
  65328. * The only supported format is currently panorama picture stored in RGBE format.
  65329. * Example of such files can be found on HDRLib: http://hdrlib.com/
  65330. */
  65331. var HDRCubeTexture = /** @class */ (function (_super) {
  65332. __extends(HDRCubeTexture, _super);
  65333. /**
  65334. * Instantiates an HDRTexture from the following parameters.
  65335. *
  65336. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  65337. * @param scene The scene the texture will be used in
  65338. * @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.
  65339. * @param noMipmap Forces to not generate the mipmap if true
  65340. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  65341. * @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)
  65342. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  65343. */
  65344. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  65345. if (noMipmap === void 0) { noMipmap = false; }
  65346. if (generateHarmonics === void 0) { generateHarmonics = true; }
  65347. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  65348. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  65349. if (onLoad === void 0) { onLoad = null; }
  65350. if (onError === void 0) { onError = null; }
  65351. var _this = _super.call(this, scene) || this;
  65352. _this._useInGammaSpace = false;
  65353. _this._generateHarmonics = true;
  65354. _this._isBABYLONPreprocessed = false;
  65355. _this._onLoad = null;
  65356. _this._onError = null;
  65357. /**
  65358. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  65359. */
  65360. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  65361. /**
  65362. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  65363. * This is usefull at run time to apply the good shader.
  65364. */
  65365. _this.isPMREM = false;
  65366. _this._isBlocking = true;
  65367. if (!url) {
  65368. return _this;
  65369. }
  65370. _this.name = url;
  65371. _this.url = url;
  65372. _this.hasAlpha = false;
  65373. _this.isCube = true;
  65374. _this._textureMatrix = BABYLON.Matrix.Identity();
  65375. _this._onLoad = onLoad;
  65376. _this._onError = onError;
  65377. _this.gammaSpace = false;
  65378. var caps = scene.getEngine().getCaps();
  65379. if (size) {
  65380. _this._isBABYLONPreprocessed = false;
  65381. _this._noMipmap = noMipmap;
  65382. _this._size = size;
  65383. _this._useInGammaSpace = useInGammaSpace;
  65384. _this._usePMREMGenerator = usePMREMGenerator &&
  65385. caps.textureLOD &&
  65386. caps.textureFloat &&
  65387. !_this._useInGammaSpace;
  65388. }
  65389. else {
  65390. _this._isBABYLONPreprocessed = true;
  65391. _this._noMipmap = false;
  65392. _this._useInGammaSpace = false;
  65393. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  65394. !_this._useInGammaSpace;
  65395. }
  65396. _this.isPMREM = _this._usePMREMGenerator;
  65397. _this._texture = _this._getFromCache(url, _this._noMipmap);
  65398. if (!_this._texture) {
  65399. if (!scene.useDelayedTextureLoading) {
  65400. _this.loadTexture();
  65401. }
  65402. else {
  65403. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  65404. }
  65405. }
  65406. return _this;
  65407. }
  65408. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  65409. /**
  65410. * Gets wether or not the texture is blocking during loading.
  65411. */
  65412. get: function () {
  65413. return this._isBlocking;
  65414. },
  65415. /**
  65416. * Sets wether or not the texture is blocking during loading.
  65417. */
  65418. set: function (value) {
  65419. this._isBlocking = value;
  65420. },
  65421. enumerable: true,
  65422. configurable: true
  65423. });
  65424. /**
  65425. * Occurs when the file is a preprocessed .babylon.hdr file.
  65426. */
  65427. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  65428. var _this = this;
  65429. var mipLevels = 0;
  65430. var floatArrayView = null;
  65431. var scene = this.getScene();
  65432. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  65433. var mips = new Array();
  65434. if (!floatArrayView) {
  65435. return mips;
  65436. }
  65437. var startIndex = 30;
  65438. for (var level = 0; level < mipLevels; level++) {
  65439. mips.push([]);
  65440. // Fill each pixel of the mip level.
  65441. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  65442. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  65443. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  65444. mips[level].push(faceData);
  65445. startIndex += faceSize;
  65446. }
  65447. }
  65448. return mips;
  65449. } : null;
  65450. var callback = function (buffer) {
  65451. var scene = _this.getScene();
  65452. if (!scene) {
  65453. return null;
  65454. }
  65455. // Create Native Array Views
  65456. var intArrayView = new Int32Array(buffer);
  65457. floatArrayView = new Float32Array(buffer);
  65458. // Fill header.
  65459. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  65460. _this._size = intArrayView[1]; // CubeMap max mip face size.
  65461. // Update Texture Information.
  65462. if (!_this._texture) {
  65463. return null;
  65464. }
  65465. _this._texture.updateSize(_this._size, _this._size);
  65466. // Fill polynomial information.
  65467. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  65468. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  65469. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  65470. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  65471. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  65472. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  65473. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  65474. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  65475. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  65476. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  65477. _this.sphericalPolynomial = sphericalPolynomial;
  65478. // Fill pixel data.
  65479. mipLevels = intArrayView[29]; // Number of mip levels.
  65480. var startIndex = 30;
  65481. var data = [];
  65482. var faceSize = Math.pow(_this._size, 2) * 3;
  65483. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  65484. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  65485. startIndex += faceSize;
  65486. }
  65487. var results = [];
  65488. var byteArray = null;
  65489. // Push each faces.
  65490. for (var k = 0; k < 6; k++) {
  65491. var dataFace = null;
  65492. // To be deprecated.
  65493. if (version === 1) {
  65494. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  65495. dataFace = data[j];
  65496. }
  65497. // If special cases.
  65498. if (!mipmapGenerator && dataFace) {
  65499. if (!scene.getEngine().getCaps().textureFloat) {
  65500. // 3 channels of 1 bytes per pixel in bytes.
  65501. var byteBuffer = new ArrayBuffer(faceSize);
  65502. byteArray = new Uint8Array(byteBuffer);
  65503. }
  65504. for (var i = 0; i < _this._size * _this._size; i++) {
  65505. // Put in gamma space if requested.
  65506. if (_this._useInGammaSpace) {
  65507. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  65508. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  65509. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  65510. }
  65511. // Convert to int texture for fallback.
  65512. if (byteArray) {
  65513. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  65514. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  65515. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  65516. // May use luminance instead if the result is not accurate.
  65517. var max = Math.max(Math.max(r, g), b);
  65518. if (max > 255) {
  65519. var scale = 255 / max;
  65520. r *= scale;
  65521. g *= scale;
  65522. b *= scale;
  65523. }
  65524. byteArray[(i * 3) + 0] = r;
  65525. byteArray[(i * 3) + 1] = g;
  65526. byteArray[(i * 3) + 2] = b;
  65527. }
  65528. }
  65529. }
  65530. // Fill the array accordingly.
  65531. if (byteArray) {
  65532. results.push(byteArray);
  65533. }
  65534. else {
  65535. results.push(dataFace);
  65536. }
  65537. }
  65538. return results;
  65539. };
  65540. if (scene) {
  65541. 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);
  65542. }
  65543. };
  65544. /**
  65545. * Occurs when the file is raw .hdr file.
  65546. */
  65547. HDRCubeTexture.prototype.loadHDRTexture = function () {
  65548. var _this = this;
  65549. var callback = function (buffer) {
  65550. var scene = _this.getScene();
  65551. if (!scene) {
  65552. return null;
  65553. }
  65554. // Extract the raw linear data.
  65555. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  65556. // Generate harmonics if needed.
  65557. if (_this._generateHarmonics) {
  65558. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  65559. _this.sphericalPolynomial = sphericalPolynomial;
  65560. }
  65561. var results = [];
  65562. var byteArray = null;
  65563. // Push each faces.
  65564. for (var j = 0; j < 6; j++) {
  65565. // Create uintarray fallback.
  65566. if (!scene.getEngine().getCaps().textureFloat) {
  65567. // 3 channels of 1 bytes per pixel in bytes.
  65568. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  65569. byteArray = new Uint8Array(byteBuffer);
  65570. }
  65571. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  65572. // If special cases.
  65573. if (_this._useInGammaSpace || byteArray) {
  65574. for (var i = 0; i < _this._size * _this._size; i++) {
  65575. // Put in gamma space if requested.
  65576. if (_this._useInGammaSpace) {
  65577. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  65578. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  65579. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  65580. }
  65581. // Convert to int texture for fallback.
  65582. if (byteArray) {
  65583. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  65584. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  65585. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  65586. // May use luminance instead if the result is not accurate.
  65587. var max = Math.max(Math.max(r, g), b);
  65588. if (max > 255) {
  65589. var scale = 255 / max;
  65590. r *= scale;
  65591. g *= scale;
  65592. b *= scale;
  65593. }
  65594. byteArray[(i * 3) + 0] = r;
  65595. byteArray[(i * 3) + 1] = g;
  65596. byteArray[(i * 3) + 2] = b;
  65597. }
  65598. }
  65599. }
  65600. if (byteArray) {
  65601. results.push(byteArray);
  65602. }
  65603. else {
  65604. results.push(dataFace);
  65605. }
  65606. }
  65607. return results;
  65608. };
  65609. var mipmapGenerator = null;
  65610. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  65611. // if (!this._noMipmap &&
  65612. // this._usePMREMGenerator) {
  65613. // mipmapGenerator = (data: ArrayBufferView[]) => {
  65614. // // Custom setup of the generator matching with the PBR shader values.
  65615. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  65616. // this._size,
  65617. // this._size,
  65618. // 0,
  65619. // 3,
  65620. // this.getScene().getEngine().getCaps().textureFloat,
  65621. // 2048,
  65622. // 0.25,
  65623. // false,
  65624. // true);
  65625. // return generator.filterCubeMap();
  65626. // };
  65627. // }
  65628. var scene = this.getScene();
  65629. if (scene) {
  65630. 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);
  65631. }
  65632. };
  65633. /**
  65634. * Starts the loading process of the texture.
  65635. */
  65636. HDRCubeTexture.prototype.loadTexture = function () {
  65637. if (this._isBABYLONPreprocessed) {
  65638. this.loadBabylonTexture();
  65639. }
  65640. else {
  65641. this.loadHDRTexture();
  65642. }
  65643. };
  65644. HDRCubeTexture.prototype.clone = function () {
  65645. var scene = this.getScene();
  65646. if (!scene) {
  65647. return this;
  65648. }
  65649. var size = (this._isBABYLONPreprocessed ? null : this._size);
  65650. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  65651. // Base texture
  65652. newTexture.level = this.level;
  65653. newTexture.wrapU = this.wrapU;
  65654. newTexture.wrapV = this.wrapV;
  65655. newTexture.coordinatesIndex = this.coordinatesIndex;
  65656. newTexture.coordinatesMode = this.coordinatesMode;
  65657. return newTexture;
  65658. };
  65659. // Methods
  65660. HDRCubeTexture.prototype.delayLoad = function () {
  65661. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  65662. return;
  65663. }
  65664. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  65665. this._texture = this._getFromCache(this.url, this._noMipmap);
  65666. if (!this._texture) {
  65667. this.loadTexture();
  65668. }
  65669. };
  65670. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  65671. return this._textureMatrix;
  65672. };
  65673. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  65674. this._textureMatrix = value;
  65675. };
  65676. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  65677. var texture = null;
  65678. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  65679. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  65680. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  65681. texture.name = parsedTexture.name;
  65682. texture.hasAlpha = parsedTexture.hasAlpha;
  65683. texture.level = parsedTexture.level;
  65684. texture.coordinatesMode = parsedTexture.coordinatesMode;
  65685. texture.isBlocking = parsedTexture.isBlocking;
  65686. }
  65687. return texture;
  65688. };
  65689. HDRCubeTexture.prototype.serialize = function () {
  65690. if (!this.name) {
  65691. return null;
  65692. }
  65693. var serializationObject = {};
  65694. serializationObject.name = this.name;
  65695. serializationObject.hasAlpha = this.hasAlpha;
  65696. serializationObject.isCube = true;
  65697. serializationObject.level = this.level;
  65698. serializationObject.size = this._size;
  65699. serializationObject.coordinatesMode = this.coordinatesMode;
  65700. serializationObject.useInGammaSpace = this._useInGammaSpace;
  65701. serializationObject.generateHarmonics = this._generateHarmonics;
  65702. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  65703. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  65704. serializationObject.customType = "BABYLON.HDRCubeTexture";
  65705. serializationObject.noMipmap = this._noMipmap;
  65706. serializationObject.isBlocking = this._isBlocking;
  65707. return serializationObject;
  65708. };
  65709. /**
  65710. * Saves as a file the data contained in the texture in a binary format.
  65711. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  65712. * as the spherical used in the lighting.
  65713. * @param url The HDR file url.
  65714. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  65715. * @param onError Method called if any error happens during download.
  65716. * @return The packed binary data.
  65717. */
  65718. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  65719. if (onError === void 0) { onError = null; }
  65720. var callback = function (buffer) {
  65721. var data = new Blob([buffer], { type: 'application/octet-stream' });
  65722. // Returns a URL you can use as a href.
  65723. var objUrl = window.URL.createObjectURL(data);
  65724. // Simulates a link to it and click to dowload.
  65725. var a = document.createElement("a");
  65726. document.body.appendChild(a);
  65727. a.style.display = "none";
  65728. a.href = objUrl;
  65729. a.download = "envmap.babylon.hdr";
  65730. a.click();
  65731. };
  65732. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  65733. };
  65734. /**
  65735. * Serializes the data contained in the texture in a binary format.
  65736. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  65737. * as the spherical used in the lighting.
  65738. * @param url The HDR file url.
  65739. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  65740. * @param onError Method called if any error happens during download.
  65741. * @return The packed binary data.
  65742. */
  65743. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  65744. if (onError === void 0) { onError = null; }
  65745. // Needs the url tho create the texture.
  65746. if (!url) {
  65747. return;
  65748. }
  65749. // Check Power of two size.
  65750. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  65751. return;
  65752. }
  65753. // Coming Back in 3.x.
  65754. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  65755. };
  65756. HDRCubeTexture._facesMapping = [
  65757. "right",
  65758. "left",
  65759. "up",
  65760. "down",
  65761. "front",
  65762. "back"
  65763. ];
  65764. return HDRCubeTexture;
  65765. }(BABYLON.BaseTexture));
  65766. BABYLON.HDRCubeTexture = HDRCubeTexture;
  65767. })(BABYLON || (BABYLON = {}));
  65768. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  65769. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  65770. // Huge respect for a such great lib.
  65771. // Earcut license:
  65772. // Copyright (c) 2016, Mapbox
  65773. //
  65774. // Permission to use, copy, modify, and/or distribute this software for any purpose
  65775. // with or without fee is hereby granted, provided that the above copyright notice
  65776. // and this permission notice appear in all copies.
  65777. //
  65778. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  65779. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  65780. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  65781. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  65782. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  65783. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  65784. // THIS SOFTWARE.
  65785. var Earcut;
  65786. (function (Earcut) {
  65787. /**
  65788. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  65789. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  65790. * @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).
  65791. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  65792. */
  65793. function earcut(data, holeIndices, dim) {
  65794. dim = dim || 2;
  65795. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  65796. if (!outerNode)
  65797. return triangles;
  65798. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  65799. if (hasHoles)
  65800. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  65801. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  65802. if (data.length > 80 * dim) {
  65803. minX = maxX = data[0];
  65804. minY = maxY = data[1];
  65805. for (var i = dim; i < outerLen; i += dim) {
  65806. x = data[i];
  65807. y = data[i + 1];
  65808. if (x < minX)
  65809. minX = x;
  65810. if (y < minY)
  65811. minY = y;
  65812. if (x > maxX)
  65813. maxX = x;
  65814. if (y > maxY)
  65815. maxY = y;
  65816. }
  65817. // minX, minY and size are later used to transform coords into integers for z-order calculation
  65818. size = Math.max(maxX - minX, maxY - minY);
  65819. }
  65820. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  65821. return triangles;
  65822. }
  65823. Earcut.earcut = earcut;
  65824. var Node = /** @class */ (function () {
  65825. function Node(i, x, y) {
  65826. this.i = i;
  65827. this.x = x;
  65828. this.y = y;
  65829. this.prev = null;
  65830. this.next = null;
  65831. this.z = null;
  65832. this.prevZ = null;
  65833. this.nextZ = null;
  65834. this.steiner = false;
  65835. }
  65836. return Node;
  65837. }());
  65838. // create a circular doubly linked list from polygon points in the specified winding order
  65839. function linkedList(data, start, end, dim, clockwise) {
  65840. var i, last = null;
  65841. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  65842. for (i = start; i < end; i += dim)
  65843. last = insertNode(i, data[i], data[i + 1], last);
  65844. }
  65845. else {
  65846. for (i = end - dim; i >= start; i -= dim)
  65847. last = insertNode(i, data[i], data[i + 1], last);
  65848. }
  65849. if (last && equals(last, last.next)) {
  65850. removeNode(last);
  65851. last = last.next;
  65852. }
  65853. return last;
  65854. }
  65855. // eliminate colinear or duplicate points
  65856. function filterPoints(start, end) {
  65857. if (!start)
  65858. return start;
  65859. if (!end)
  65860. end = start;
  65861. var p = start, again;
  65862. do {
  65863. again = false;
  65864. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  65865. removeNode(p);
  65866. p = end = p.prev;
  65867. if (p === p.next)
  65868. return undefined;
  65869. again = true;
  65870. }
  65871. else {
  65872. p = p.next;
  65873. }
  65874. } while (again || p !== end);
  65875. return end;
  65876. }
  65877. // main ear slicing loop which triangulates a polygon (given as a linked list)
  65878. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  65879. if (!ear)
  65880. return;
  65881. // interlink polygon nodes in z-order
  65882. if (!pass && size)
  65883. indexCurve(ear, minX, minY, size);
  65884. var stop = ear, prev, next;
  65885. // iterate through ears, slicing them one by one
  65886. while (ear.prev !== ear.next) {
  65887. prev = ear.prev;
  65888. next = ear.next;
  65889. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  65890. // cut off the triangle
  65891. triangles.push(prev.i / dim);
  65892. triangles.push(ear.i / dim);
  65893. triangles.push(next.i / dim);
  65894. removeNode(ear);
  65895. // skipping the next vertice leads to less sliver triangles
  65896. ear = next.next;
  65897. stop = next.next;
  65898. continue;
  65899. }
  65900. ear = next;
  65901. // if we looped through the whole remaining polygon and can't find any more ears
  65902. if (ear === stop) {
  65903. // try filtering points and slicing again
  65904. if (!pass) {
  65905. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  65906. // if this didn't work, try curing all small self-intersections locally
  65907. }
  65908. else if (pass === 1) {
  65909. ear = cureLocalIntersections(ear, triangles, dim);
  65910. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  65911. // as a last resort, try splitting the remaining polygon into two
  65912. }
  65913. else if (pass === 2) {
  65914. splitEarcut(ear, triangles, dim, minX, minY, size);
  65915. }
  65916. break;
  65917. }
  65918. }
  65919. }
  65920. // check whether a polygon node forms a valid ear with adjacent nodes
  65921. function isEar(ear) {
  65922. var a = ear.prev, b = ear, c = ear.next;
  65923. if (area(a, b, c) >= 0)
  65924. return false; // reflex, can't be an ear
  65925. // now make sure we don't have other points inside the potential ear
  65926. var p = ear.next.next;
  65927. while (p !== ear.prev) {
  65928. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  65929. area(p.prev, p, p.next) >= 0)
  65930. return false;
  65931. p = p.next;
  65932. }
  65933. return true;
  65934. }
  65935. function isEarHashed(ear, minX, minY, size) {
  65936. var a = ear.prev, b = ear, c = ear.next;
  65937. if (area(a, b, c) >= 0)
  65938. return false; // reflex, can't be an ear
  65939. // triangle bbox; min & max are calculated like this for speed
  65940. 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);
  65941. // z-order range for the current triangle bbox;
  65942. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  65943. // first look for points inside the triangle in increasing z-order
  65944. var p = ear.nextZ;
  65945. while (p && p.z <= maxZ) {
  65946. if (p !== ear.prev &&
  65947. p !== ear.next &&
  65948. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  65949. area(p.prev, p, p.next) >= 0)
  65950. return false;
  65951. p = p.nextZ;
  65952. }
  65953. // then look for points in decreasing z-order
  65954. p = ear.prevZ;
  65955. while (p && p.z >= minZ) {
  65956. if (p !== ear.prev &&
  65957. p !== ear.next &&
  65958. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  65959. area(p.prev, p, p.next) >= 0)
  65960. return false;
  65961. p = p.prevZ;
  65962. }
  65963. return true;
  65964. }
  65965. // go through all polygon nodes and cure small local self-intersections
  65966. function cureLocalIntersections(start, triangles, dim) {
  65967. var p = start;
  65968. do {
  65969. var a = p.prev, b = p.next.next;
  65970. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  65971. triangles.push(a.i / dim);
  65972. triangles.push(p.i / dim);
  65973. triangles.push(b.i / dim);
  65974. // remove two nodes involved
  65975. removeNode(p);
  65976. removeNode(p.next);
  65977. p = start = b;
  65978. }
  65979. p = p.next;
  65980. } while (p !== start);
  65981. return p;
  65982. }
  65983. // try splitting polygon into two and triangulate them independently
  65984. function splitEarcut(start, triangles, dim, minX, minY, size) {
  65985. // look for a valid diagonal that divides the polygon into two
  65986. var a = start;
  65987. do {
  65988. var b = a.next.next;
  65989. while (b !== a.prev) {
  65990. if (a.i !== b.i && isValidDiagonal(a, b)) {
  65991. // split the polygon in two by the diagonal
  65992. var c = splitPolygon(a, b);
  65993. // filter colinear points around the cuts
  65994. a = filterPoints(a, a.next);
  65995. c = filterPoints(c, c.next);
  65996. // run earcut on each half
  65997. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  65998. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  65999. return;
  66000. }
  66001. b = b.next;
  66002. }
  66003. a = a.next;
  66004. } while (a !== start);
  66005. }
  66006. // link every hole into the outer loop, producing a single-ring polygon without holes
  66007. function eliminateHoles(data, holeIndices, outerNode, dim) {
  66008. var queue = [], i, len, start, end, list;
  66009. for (i = 0, len = holeIndices.length; i < len; i++) {
  66010. start = holeIndices[i] * dim;
  66011. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  66012. list = linkedList(data, start, end, dim, false);
  66013. if (list === list.next)
  66014. list.steiner = true;
  66015. queue.push(getLeftmost(list));
  66016. }
  66017. queue.sort(compareX);
  66018. // process holes from left to right
  66019. for (i = 0; i < queue.length; i++) {
  66020. eliminateHole(queue[i], outerNode);
  66021. outerNode = filterPoints(outerNode, outerNode.next);
  66022. }
  66023. return outerNode;
  66024. }
  66025. function compareX(a, b) {
  66026. return a.x - b.x;
  66027. }
  66028. // find a bridge between vertices that connects hole with an outer ring and and link it
  66029. function eliminateHole(hole, outerNode) {
  66030. outerNode = findHoleBridge(hole, outerNode);
  66031. if (outerNode) {
  66032. var b = splitPolygon(outerNode, hole);
  66033. filterPoints(b, b.next);
  66034. }
  66035. }
  66036. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  66037. function findHoleBridge(hole, outerNode) {
  66038. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  66039. // find a segment intersected by a ray from the hole's leftmost point to the left;
  66040. // segment's endpoint with lesser x will be potential connection point
  66041. do {
  66042. if (hy <= p.y && hy >= p.next.y) {
  66043. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  66044. if (x <= hx && x > qx) {
  66045. qx = x;
  66046. if (x === hx) {
  66047. if (hy === p.y)
  66048. return p;
  66049. if (hy === p.next.y)
  66050. return p.next;
  66051. }
  66052. m = p.x < p.next.x ? p : p.next;
  66053. }
  66054. }
  66055. p = p.next;
  66056. } while (p !== outerNode);
  66057. if (!m)
  66058. return null;
  66059. if (hx === qx)
  66060. return m.prev; // hole touches outer segment; pick lower endpoint
  66061. // look for points inside the triangle of hole point, segment intersection and endpoint;
  66062. // if there are no points found, we have a valid connection;
  66063. // otherwise choose the point of the minimum angle with the ray as connection point
  66064. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  66065. p = m.next;
  66066. while (p !== stop) {
  66067. if (hx >= p.x &&
  66068. p.x >= mx &&
  66069. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  66070. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  66071. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  66072. m = p;
  66073. tanMin = tan;
  66074. }
  66075. }
  66076. p = p.next;
  66077. }
  66078. return m;
  66079. }
  66080. // interlink polygon nodes in z-order
  66081. function indexCurve(start, minX, minY, size) {
  66082. var p = start;
  66083. do {
  66084. if (p.z === null)
  66085. p.z = zOrder(p.x, p.y, minX, minY, size);
  66086. p.prevZ = p.prev;
  66087. p.nextZ = p.next;
  66088. p = p.next;
  66089. } while (p !== start);
  66090. p.prevZ.nextZ = null;
  66091. p.prevZ = null;
  66092. sortLinked(p);
  66093. }
  66094. // Simon Tatham's linked list merge sort algorithm
  66095. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  66096. function sortLinked(list) {
  66097. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  66098. do {
  66099. p = list;
  66100. list = null;
  66101. tail = null;
  66102. numMerges = 0;
  66103. while (p) {
  66104. numMerges++;
  66105. q = p;
  66106. pSize = 0;
  66107. for (i = 0; i < inSize; i++) {
  66108. pSize++;
  66109. q = q.nextZ;
  66110. if (!q)
  66111. break;
  66112. }
  66113. qSize = inSize;
  66114. while (pSize > 0 || (qSize > 0 && q)) {
  66115. if (pSize === 0) {
  66116. e = q;
  66117. q = q.nextZ;
  66118. qSize--;
  66119. }
  66120. else if (qSize === 0 || !q) {
  66121. e = p;
  66122. p = p.nextZ;
  66123. pSize--;
  66124. }
  66125. else if (p.z <= q.z) {
  66126. e = p;
  66127. p = p.nextZ;
  66128. pSize--;
  66129. }
  66130. else {
  66131. e = q;
  66132. q = q.nextZ;
  66133. qSize--;
  66134. }
  66135. if (tail)
  66136. tail.nextZ = e;
  66137. else
  66138. list = e;
  66139. e.prevZ = tail;
  66140. tail = e;
  66141. }
  66142. p = q;
  66143. }
  66144. tail.nextZ = null;
  66145. inSize *= 2;
  66146. } while (numMerges > 1);
  66147. return list;
  66148. }
  66149. // z-order of a point given coords and size of the data bounding box
  66150. function zOrder(x, y, minX, minY, size) {
  66151. // coords are transformed into non-negative 15-bit integer range
  66152. x = 32767 * (x - minX) / size;
  66153. y = 32767 * (y - minY) / size;
  66154. x = (x | (x << 8)) & 0x00FF00FF;
  66155. x = (x | (x << 4)) & 0x0F0F0F0F;
  66156. x = (x | (x << 2)) & 0x33333333;
  66157. x = (x | (x << 1)) & 0x55555555;
  66158. y = (y | (y << 8)) & 0x00FF00FF;
  66159. y = (y | (y << 4)) & 0x0F0F0F0F;
  66160. y = (y | (y << 2)) & 0x33333333;
  66161. y = (y | (y << 1)) & 0x55555555;
  66162. return x | (y << 1);
  66163. }
  66164. // find the leftmost node of a polygon ring
  66165. function getLeftmost(start) {
  66166. var p = start, leftmost = start;
  66167. do {
  66168. if (p.x < leftmost.x)
  66169. leftmost = p;
  66170. p = p.next;
  66171. } while (p !== start);
  66172. return leftmost;
  66173. }
  66174. // check if a point lies within a convex triangle
  66175. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  66176. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  66177. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  66178. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  66179. }
  66180. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  66181. function isValidDiagonal(a, b) {
  66182. return a.next.i !== b.i &&
  66183. a.prev.i !== b.i &&
  66184. !intersectsPolygon(a, b) &&
  66185. locallyInside(a, b) &&
  66186. locallyInside(b, a) &&
  66187. middleInside(a, b);
  66188. }
  66189. // signed area of a triangle
  66190. function area(p, q, r) {
  66191. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  66192. }
  66193. // check if two points are equal
  66194. function equals(p1, p2) {
  66195. return p1.x === p2.x && p1.y === p2.y;
  66196. }
  66197. // check if two segments intersect
  66198. function intersects(p1, q1, p2, q2) {
  66199. if ((equals(p1, q1) && equals(p2, q2)) ||
  66200. (equals(p1, q2) && equals(p2, q1)))
  66201. return true;
  66202. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  66203. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  66204. }
  66205. // check if a polygon diagonal intersects any polygon segments
  66206. function intersectsPolygon(a, b) {
  66207. var p = a;
  66208. do {
  66209. if (p.i !== a.i &&
  66210. p.next.i !== a.i &&
  66211. p.i !== b.i &&
  66212. p.next.i !== b.i &&
  66213. intersects(p, p.next, a, b))
  66214. return true;
  66215. p = p.next;
  66216. } while (p !== a);
  66217. return false;
  66218. }
  66219. // check if a polygon diagonal is locally inside the polygon
  66220. function locallyInside(a, b) {
  66221. return area(a.prev, a, a.next) < 0
  66222. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  66223. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  66224. }
  66225. // check if the middle point of a polygon diagonal is inside the polygon
  66226. function middleInside(a, b) {
  66227. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  66228. do {
  66229. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  66230. inside = !inside;
  66231. p = p.next;
  66232. } while (p !== a);
  66233. return inside;
  66234. }
  66235. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  66236. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  66237. function splitPolygon(a, b) {
  66238. 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;
  66239. a.next = b;
  66240. b.prev = a;
  66241. a2.next = an;
  66242. an.prev = a2;
  66243. b2.next = a2;
  66244. a2.prev = b2;
  66245. bp.next = b2;
  66246. b2.prev = bp;
  66247. return b2;
  66248. }
  66249. // create a node and optionally link it with previous one (in a circular doubly linked list)
  66250. function insertNode(i, x, y, last) {
  66251. var p = new Node(i, x, y);
  66252. if (!last) {
  66253. p.prev = p;
  66254. p.next = p;
  66255. }
  66256. else {
  66257. p.next = last.next;
  66258. p.prev = last;
  66259. last.next.prev = p;
  66260. last.next = p;
  66261. }
  66262. return p;
  66263. }
  66264. function removeNode(p) {
  66265. p.next.prev = p.prev;
  66266. p.prev.next = p.next;
  66267. if (p.prevZ)
  66268. p.prevZ.nextZ = p.nextZ;
  66269. if (p.nextZ)
  66270. p.nextZ.prevZ = p.prevZ;
  66271. }
  66272. /**
  66273. * return a percentage difference between the polygon area and its triangulation area;
  66274. * used to verify correctness of triangulation
  66275. */
  66276. function deviation(data, holeIndices, dim, triangles) {
  66277. var hasHoles = holeIndices && holeIndices.length;
  66278. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  66279. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  66280. if (hasHoles) {
  66281. for (var i = 0, len = holeIndices.length; i < len; i++) {
  66282. var start = holeIndices[i] * dim;
  66283. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  66284. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  66285. }
  66286. }
  66287. var trianglesArea = 0;
  66288. for (i = 0; i < triangles.length; i += 3) {
  66289. var a = triangles[i] * dim;
  66290. var b = triangles[i + 1] * dim;
  66291. var c = triangles[i + 2] * dim;
  66292. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  66293. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  66294. }
  66295. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  66296. }
  66297. Earcut.deviation = deviation;
  66298. ;
  66299. function signedArea(data, start, end, dim) {
  66300. var sum = 0;
  66301. for (var i = start, j = end - dim; i < end; i += dim) {
  66302. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  66303. j = i;
  66304. }
  66305. return sum;
  66306. }
  66307. /**
  66308. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  66309. */
  66310. function flatten(data) {
  66311. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  66312. for (var i = 0; i < data.length; i++) {
  66313. for (var j = 0; j < data[i].length; j++) {
  66314. for (var d = 0; d < dim; d++)
  66315. result.vertices.push(data[i][j][d]);
  66316. }
  66317. if (i > 0) {
  66318. holeIndex += data[i - 1].length;
  66319. result.holes.push(holeIndex);
  66320. }
  66321. }
  66322. return result;
  66323. }
  66324. Earcut.flatten = flatten;
  66325. ;
  66326. })(Earcut || (Earcut = {}));
  66327. //# sourceMappingURL=babylon.earcut.js.map
  66328. var BABYLON;
  66329. (function (BABYLON) {
  66330. var IndexedVector2 = /** @class */ (function (_super) {
  66331. __extends(IndexedVector2, _super);
  66332. function IndexedVector2(original, index) {
  66333. var _this = _super.call(this, original.x, original.y) || this;
  66334. _this.index = index;
  66335. return _this;
  66336. }
  66337. return IndexedVector2;
  66338. }(BABYLON.Vector2));
  66339. var PolygonPoints = /** @class */ (function () {
  66340. function PolygonPoints() {
  66341. this.elements = new Array();
  66342. }
  66343. PolygonPoints.prototype.add = function (originalPoints) {
  66344. var _this = this;
  66345. var result = new Array();
  66346. originalPoints.forEach(function (point) {
  66347. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  66348. var newPoint = new IndexedVector2(point, _this.elements.length);
  66349. result.push(newPoint);
  66350. _this.elements.push(newPoint);
  66351. }
  66352. });
  66353. return result;
  66354. };
  66355. PolygonPoints.prototype.computeBounds = function () {
  66356. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  66357. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  66358. this.elements.forEach(function (point) {
  66359. // x
  66360. if (point.x < lmin.x) {
  66361. lmin.x = point.x;
  66362. }
  66363. else if (point.x > lmax.x) {
  66364. lmax.x = point.x;
  66365. }
  66366. // y
  66367. if (point.y < lmin.y) {
  66368. lmin.y = point.y;
  66369. }
  66370. else if (point.y > lmax.y) {
  66371. lmax.y = point.y;
  66372. }
  66373. });
  66374. return {
  66375. min: lmin,
  66376. max: lmax,
  66377. width: lmax.x - lmin.x,
  66378. height: lmax.y - lmin.y
  66379. };
  66380. };
  66381. return PolygonPoints;
  66382. }());
  66383. var Polygon = /** @class */ (function () {
  66384. function Polygon() {
  66385. }
  66386. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  66387. return [
  66388. new BABYLON.Vector2(xmin, ymin),
  66389. new BABYLON.Vector2(xmax, ymin),
  66390. new BABYLON.Vector2(xmax, ymax),
  66391. new BABYLON.Vector2(xmin, ymax)
  66392. ];
  66393. };
  66394. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  66395. if (cx === void 0) { cx = 0; }
  66396. if (cy === void 0) { cy = 0; }
  66397. if (numberOfSides === void 0) { numberOfSides = 32; }
  66398. var result = new Array();
  66399. var angle = 0;
  66400. var increment = (Math.PI * 2) / numberOfSides;
  66401. for (var i = 0; i < numberOfSides; i++) {
  66402. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  66403. angle -= increment;
  66404. }
  66405. return result;
  66406. };
  66407. Polygon.Parse = function (input) {
  66408. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  66409. var i, result = [];
  66410. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  66411. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  66412. }
  66413. return result;
  66414. };
  66415. Polygon.StartingAt = function (x, y) {
  66416. return BABYLON.Path2.StartingAt(x, y);
  66417. };
  66418. return Polygon;
  66419. }());
  66420. BABYLON.Polygon = Polygon;
  66421. var PolygonMeshBuilder = /** @class */ (function () {
  66422. function PolygonMeshBuilder(name, contours, scene) {
  66423. this._points = new PolygonPoints();
  66424. this._outlinepoints = new PolygonPoints();
  66425. this._holes = new Array();
  66426. this._epoints = new Array();
  66427. this._eholes = new Array();
  66428. this._name = name;
  66429. this._scene = scene;
  66430. var points;
  66431. if (contours instanceof BABYLON.Path2) {
  66432. points = contours.getPoints();
  66433. }
  66434. else {
  66435. points = contours;
  66436. }
  66437. this._addToepoint(points);
  66438. this._points.add(points);
  66439. this._outlinepoints.add(points);
  66440. }
  66441. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  66442. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  66443. var p = points_1[_i];
  66444. this._epoints.push(p.x, p.y);
  66445. }
  66446. };
  66447. PolygonMeshBuilder.prototype.addHole = function (hole) {
  66448. this._points.add(hole);
  66449. var holepoints = new PolygonPoints();
  66450. holepoints.add(hole);
  66451. this._holes.push(holepoints);
  66452. this._eholes.push(this._epoints.length / 2);
  66453. this._addToepoint(hole);
  66454. return this;
  66455. };
  66456. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  66457. var _this = this;
  66458. if (updatable === void 0) { updatable = false; }
  66459. if (depth === void 0) { depth = 0; }
  66460. var result = new BABYLON.Mesh(this._name, this._scene);
  66461. var normals = new Array();
  66462. var positions = new Array();
  66463. var uvs = new Array();
  66464. var bounds = this._points.computeBounds();
  66465. this._points.elements.forEach(function (p) {
  66466. normals.push(0, 1.0, 0);
  66467. positions.push(p.x, 0, p.y);
  66468. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  66469. });
  66470. var indices = new Array();
  66471. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  66472. for (var i = 0; i < res.length; i++) {
  66473. indices.push(res[i]);
  66474. }
  66475. if (depth > 0) {
  66476. var positionscount = (positions.length / 3); //get the current pointcount
  66477. this._points.elements.forEach(function (p) {
  66478. normals.push(0, -1.0, 0);
  66479. positions.push(p.x, -depth, p.y);
  66480. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  66481. });
  66482. var totalCount = indices.length;
  66483. for (var i = 0; i < totalCount; i += 3) {
  66484. var i0 = indices[i + 0];
  66485. var i1 = indices[i + 1];
  66486. var i2 = indices[i + 2];
  66487. indices.push(i2 + positionscount);
  66488. indices.push(i1 + positionscount);
  66489. indices.push(i0 + positionscount);
  66490. }
  66491. //Add the sides
  66492. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  66493. this._holes.forEach(function (hole) {
  66494. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  66495. });
  66496. }
  66497. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  66498. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  66499. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  66500. result.setIndices(indices);
  66501. return result;
  66502. };
  66503. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  66504. var StartIndex = positions.length / 3;
  66505. var ulength = 0;
  66506. for (var i = 0; i < points.elements.length; i++) {
  66507. var p = points.elements[i];
  66508. var p1;
  66509. if ((i + 1) > points.elements.length - 1) {
  66510. p1 = points.elements[0];
  66511. }
  66512. else {
  66513. p1 = points.elements[i + 1];
  66514. }
  66515. positions.push(p.x, 0, p.y);
  66516. positions.push(p.x, -depth, p.y);
  66517. positions.push(p1.x, 0, p1.y);
  66518. positions.push(p1.x, -depth, p1.y);
  66519. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  66520. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  66521. var v3 = v2.subtract(v1);
  66522. var v4 = new BABYLON.Vector3(0, 1, 0);
  66523. var vn = BABYLON.Vector3.Cross(v3, v4);
  66524. vn = vn.normalize();
  66525. uvs.push(ulength / bounds.width, 0);
  66526. uvs.push(ulength / bounds.width, 1);
  66527. ulength += v3.length();
  66528. uvs.push((ulength / bounds.width), 0);
  66529. uvs.push((ulength / bounds.width), 1);
  66530. if (!flip) {
  66531. normals.push(-vn.x, -vn.y, -vn.z);
  66532. normals.push(-vn.x, -vn.y, -vn.z);
  66533. normals.push(-vn.x, -vn.y, -vn.z);
  66534. normals.push(-vn.x, -vn.y, -vn.z);
  66535. indices.push(StartIndex);
  66536. indices.push(StartIndex + 1);
  66537. indices.push(StartIndex + 2);
  66538. indices.push(StartIndex + 1);
  66539. indices.push(StartIndex + 3);
  66540. indices.push(StartIndex + 2);
  66541. }
  66542. else {
  66543. normals.push(vn.x, vn.y, vn.z);
  66544. normals.push(vn.x, vn.y, vn.z);
  66545. normals.push(vn.x, vn.y, vn.z);
  66546. normals.push(vn.x, vn.y, vn.z);
  66547. indices.push(StartIndex);
  66548. indices.push(StartIndex + 2);
  66549. indices.push(StartIndex + 1);
  66550. indices.push(StartIndex + 1);
  66551. indices.push(StartIndex + 2);
  66552. indices.push(StartIndex + 3);
  66553. }
  66554. StartIndex += 4;
  66555. }
  66556. ;
  66557. };
  66558. return PolygonMeshBuilder;
  66559. }());
  66560. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  66561. })(BABYLON || (BABYLON = {}));
  66562. //# sourceMappingURL=babylon.polygonMesh.js.map
  66563. var BABYLON;
  66564. (function (BABYLON) {
  66565. // Unique ID when we import meshes from Babylon to CSG
  66566. var currentCSGMeshId = 0;
  66567. // # class Vertex
  66568. // Represents a vertex of a polygon. Use your own vertex class instead of this
  66569. // one to provide additional features like texture coordinates and vertex
  66570. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  66571. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  66572. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  66573. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  66574. // is not used anywhere else.
  66575. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  66576. var Vertex = /** @class */ (function () {
  66577. function Vertex(pos, normal, uv) {
  66578. this.pos = pos;
  66579. this.normal = normal;
  66580. this.uv = uv;
  66581. }
  66582. Vertex.prototype.clone = function () {
  66583. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  66584. };
  66585. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  66586. // orientation of a polygon is flipped.
  66587. Vertex.prototype.flip = function () {
  66588. this.normal = this.normal.scale(-1);
  66589. };
  66590. // Create a new vertex between this vertex and `other` by linearly
  66591. // interpolating all properties using a parameter of `t`. Subclasses should
  66592. // override this to interpolate additional properties.
  66593. Vertex.prototype.interpolate = function (other, t) {
  66594. 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));
  66595. };
  66596. return Vertex;
  66597. }());
  66598. // # class Plane
  66599. // Represents a plane in 3D space.
  66600. var Plane = /** @class */ (function () {
  66601. function Plane(normal, w) {
  66602. this.normal = normal;
  66603. this.w = w;
  66604. }
  66605. Plane.FromPoints = function (a, b, c) {
  66606. var v0 = c.subtract(a);
  66607. var v1 = b.subtract(a);
  66608. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  66609. return null;
  66610. }
  66611. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  66612. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  66613. };
  66614. Plane.prototype.clone = function () {
  66615. return new Plane(this.normal.clone(), this.w);
  66616. };
  66617. Plane.prototype.flip = function () {
  66618. this.normal.scaleInPlace(-1);
  66619. this.w = -this.w;
  66620. };
  66621. // Split `polygon` by this plane if needed, then put the polygon or polygon
  66622. // fragments in the appropriate lists. Coplanar polygons go into either
  66623. // `coplanarFront` or `coplanarBack` depending on their orientation with
  66624. // respect to this plane. Polygons in front or in back of this plane go into
  66625. // either `front` or `back`.
  66626. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  66627. var COPLANAR = 0;
  66628. var FRONT = 1;
  66629. var BACK = 2;
  66630. var SPANNING = 3;
  66631. // Classify each point as well as the entire polygon into one of the above
  66632. // four classes.
  66633. var polygonType = 0;
  66634. var types = [];
  66635. var i;
  66636. var t;
  66637. for (i = 0; i < polygon.vertices.length; i++) {
  66638. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  66639. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  66640. polygonType |= type;
  66641. types.push(type);
  66642. }
  66643. // Put the polygon in the correct list, splitting it when necessary.
  66644. switch (polygonType) {
  66645. case COPLANAR:
  66646. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  66647. break;
  66648. case FRONT:
  66649. front.push(polygon);
  66650. break;
  66651. case BACK:
  66652. back.push(polygon);
  66653. break;
  66654. case SPANNING:
  66655. var f = [], b = [];
  66656. for (i = 0; i < polygon.vertices.length; i++) {
  66657. var j = (i + 1) % polygon.vertices.length;
  66658. var ti = types[i], tj = types[j];
  66659. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  66660. if (ti !== BACK)
  66661. f.push(vi);
  66662. if (ti !== FRONT)
  66663. b.push(ti !== BACK ? vi.clone() : vi);
  66664. if ((ti | tj) === SPANNING) {
  66665. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  66666. var v = vi.interpolate(vj, t);
  66667. f.push(v);
  66668. b.push(v.clone());
  66669. }
  66670. }
  66671. var poly;
  66672. if (f.length >= 3) {
  66673. poly = new Polygon(f, polygon.shared);
  66674. if (poly.plane)
  66675. front.push(poly);
  66676. }
  66677. if (b.length >= 3) {
  66678. poly = new Polygon(b, polygon.shared);
  66679. if (poly.plane)
  66680. back.push(poly);
  66681. }
  66682. break;
  66683. }
  66684. };
  66685. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  66686. // point is on the plane.
  66687. Plane.EPSILON = 1e-5;
  66688. return Plane;
  66689. }());
  66690. // # class Polygon
  66691. // Represents a convex polygon. The vertices used to initialize a polygon must
  66692. // be coplanar and form a convex loop.
  66693. //
  66694. // Each convex polygon has a `shared` property, which is shared between all
  66695. // polygons that are clones of each other or were split from the same polygon.
  66696. // This can be used to define per-polygon properties (such as surface color).
  66697. var Polygon = /** @class */ (function () {
  66698. function Polygon(vertices, shared) {
  66699. this.vertices = vertices;
  66700. this.shared = shared;
  66701. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  66702. }
  66703. Polygon.prototype.clone = function () {
  66704. var vertices = this.vertices.map(function (v) { return v.clone(); });
  66705. return new Polygon(vertices, this.shared);
  66706. };
  66707. Polygon.prototype.flip = function () {
  66708. this.vertices.reverse().map(function (v) { v.flip(); });
  66709. this.plane.flip();
  66710. };
  66711. return Polygon;
  66712. }());
  66713. // # class Node
  66714. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  66715. // by picking a polygon to split along. That polygon (and all other coplanar
  66716. // polygons) are added directly to that node and the other polygons are added to
  66717. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  66718. // no distinction between internal and leaf nodes.
  66719. var Node = /** @class */ (function () {
  66720. function Node(polygons) {
  66721. this.plane = null;
  66722. this.front = null;
  66723. this.back = null;
  66724. this.polygons = new Array();
  66725. if (polygons) {
  66726. this.build(polygons);
  66727. }
  66728. }
  66729. Node.prototype.clone = function () {
  66730. var node = new Node();
  66731. node.plane = this.plane && this.plane.clone();
  66732. node.front = this.front && this.front.clone();
  66733. node.back = this.back && this.back.clone();
  66734. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  66735. return node;
  66736. };
  66737. // Convert solid space to empty space and empty space to solid space.
  66738. Node.prototype.invert = function () {
  66739. for (var i = 0; i < this.polygons.length; i++) {
  66740. this.polygons[i].flip();
  66741. }
  66742. if (this.plane) {
  66743. this.plane.flip();
  66744. }
  66745. if (this.front) {
  66746. this.front.invert();
  66747. }
  66748. if (this.back) {
  66749. this.back.invert();
  66750. }
  66751. var temp = this.front;
  66752. this.front = this.back;
  66753. this.back = temp;
  66754. };
  66755. // Recursively remove all polygons in `polygons` that are inside this BSP
  66756. // tree.
  66757. Node.prototype.clipPolygons = function (polygons) {
  66758. if (!this.plane)
  66759. return polygons.slice();
  66760. var front = new Array(), back = new Array();
  66761. for (var i = 0; i < polygons.length; i++) {
  66762. this.plane.splitPolygon(polygons[i], front, back, front, back);
  66763. }
  66764. if (this.front) {
  66765. front = this.front.clipPolygons(front);
  66766. }
  66767. if (this.back) {
  66768. back = this.back.clipPolygons(back);
  66769. }
  66770. else {
  66771. back = [];
  66772. }
  66773. return front.concat(back);
  66774. };
  66775. // Remove all polygons in this BSP tree that are inside the other BSP tree
  66776. // `bsp`.
  66777. Node.prototype.clipTo = function (bsp) {
  66778. this.polygons = bsp.clipPolygons(this.polygons);
  66779. if (this.front)
  66780. this.front.clipTo(bsp);
  66781. if (this.back)
  66782. this.back.clipTo(bsp);
  66783. };
  66784. // Return a list of all polygons in this BSP tree.
  66785. Node.prototype.allPolygons = function () {
  66786. var polygons = this.polygons.slice();
  66787. if (this.front)
  66788. polygons = polygons.concat(this.front.allPolygons());
  66789. if (this.back)
  66790. polygons = polygons.concat(this.back.allPolygons());
  66791. return polygons;
  66792. };
  66793. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  66794. // new polygons are filtered down to the bottom of the tree and become new
  66795. // nodes there. Each set of polygons is partitioned using the first polygon
  66796. // (no heuristic is used to pick a good split).
  66797. Node.prototype.build = function (polygons) {
  66798. if (!polygons.length)
  66799. return;
  66800. if (!this.plane)
  66801. this.plane = polygons[0].plane.clone();
  66802. var front = new Array(), back = new Array();
  66803. for (var i = 0; i < polygons.length; i++) {
  66804. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  66805. }
  66806. if (front.length) {
  66807. if (!this.front)
  66808. this.front = new Node();
  66809. this.front.build(front);
  66810. }
  66811. if (back.length) {
  66812. if (!this.back)
  66813. this.back = new Node();
  66814. this.back.build(back);
  66815. }
  66816. };
  66817. return Node;
  66818. }());
  66819. var CSG = /** @class */ (function () {
  66820. function CSG() {
  66821. this.polygons = new Array();
  66822. }
  66823. // Convert BABYLON.Mesh to BABYLON.CSG
  66824. CSG.FromMesh = function (mesh) {
  66825. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  66826. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  66827. if (mesh instanceof BABYLON.Mesh) {
  66828. mesh.computeWorldMatrix(true);
  66829. matrix = mesh.getWorldMatrix();
  66830. meshPosition = mesh.position.clone();
  66831. meshRotation = mesh.rotation.clone();
  66832. if (mesh.rotationQuaternion) {
  66833. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  66834. }
  66835. meshScaling = mesh.scaling.clone();
  66836. }
  66837. else {
  66838. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  66839. }
  66840. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  66841. var subMeshes = mesh.subMeshes;
  66842. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  66843. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  66844. vertices = [];
  66845. for (var j = 0; j < 3; j++) {
  66846. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  66847. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  66848. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  66849. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  66850. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  66851. vertex = new Vertex(position, normal, uv);
  66852. vertices.push(vertex);
  66853. }
  66854. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  66855. // To handle the case of degenerated triangle
  66856. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  66857. if (polygon.plane)
  66858. polygons.push(polygon);
  66859. }
  66860. }
  66861. var csg = CSG.FromPolygons(polygons);
  66862. csg.matrix = matrix;
  66863. csg.position = meshPosition;
  66864. csg.rotation = meshRotation;
  66865. csg.scaling = meshScaling;
  66866. csg.rotationQuaternion = meshRotationQuaternion;
  66867. currentCSGMeshId++;
  66868. return csg;
  66869. };
  66870. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  66871. CSG.FromPolygons = function (polygons) {
  66872. var csg = new CSG();
  66873. csg.polygons = polygons;
  66874. return csg;
  66875. };
  66876. CSG.prototype.clone = function () {
  66877. var csg = new CSG();
  66878. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  66879. csg.copyTransformAttributes(this);
  66880. return csg;
  66881. };
  66882. CSG.prototype.union = function (csg) {
  66883. var a = new Node(this.clone().polygons);
  66884. var b = new Node(csg.clone().polygons);
  66885. a.clipTo(b);
  66886. b.clipTo(a);
  66887. b.invert();
  66888. b.clipTo(a);
  66889. b.invert();
  66890. a.build(b.allPolygons());
  66891. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  66892. };
  66893. CSG.prototype.unionInPlace = function (csg) {
  66894. var a = new Node(this.polygons);
  66895. var b = new Node(csg.polygons);
  66896. a.clipTo(b);
  66897. b.clipTo(a);
  66898. b.invert();
  66899. b.clipTo(a);
  66900. b.invert();
  66901. a.build(b.allPolygons());
  66902. this.polygons = a.allPolygons();
  66903. };
  66904. CSG.prototype.subtract = function (csg) {
  66905. var a = new Node(this.clone().polygons);
  66906. var b = new Node(csg.clone().polygons);
  66907. a.invert();
  66908. a.clipTo(b);
  66909. b.clipTo(a);
  66910. b.invert();
  66911. b.clipTo(a);
  66912. b.invert();
  66913. a.build(b.allPolygons());
  66914. a.invert();
  66915. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  66916. };
  66917. CSG.prototype.subtractInPlace = function (csg) {
  66918. var a = new Node(this.polygons);
  66919. var b = new Node(csg.polygons);
  66920. a.invert();
  66921. a.clipTo(b);
  66922. b.clipTo(a);
  66923. b.invert();
  66924. b.clipTo(a);
  66925. b.invert();
  66926. a.build(b.allPolygons());
  66927. a.invert();
  66928. this.polygons = a.allPolygons();
  66929. };
  66930. CSG.prototype.intersect = function (csg) {
  66931. var a = new Node(this.clone().polygons);
  66932. var b = new Node(csg.clone().polygons);
  66933. a.invert();
  66934. b.clipTo(a);
  66935. b.invert();
  66936. a.clipTo(b);
  66937. b.clipTo(a);
  66938. a.build(b.allPolygons());
  66939. a.invert();
  66940. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  66941. };
  66942. CSG.prototype.intersectInPlace = function (csg) {
  66943. var a = new Node(this.polygons);
  66944. var b = new Node(csg.polygons);
  66945. a.invert();
  66946. b.clipTo(a);
  66947. b.invert();
  66948. a.clipTo(b);
  66949. b.clipTo(a);
  66950. a.build(b.allPolygons());
  66951. a.invert();
  66952. this.polygons = a.allPolygons();
  66953. };
  66954. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  66955. // not modified.
  66956. CSG.prototype.inverse = function () {
  66957. var csg = this.clone();
  66958. csg.inverseInPlace();
  66959. return csg;
  66960. };
  66961. CSG.prototype.inverseInPlace = function () {
  66962. this.polygons.map(function (p) { p.flip(); });
  66963. };
  66964. // This is used to keep meshes transformations so they can be restored
  66965. // when we build back a Babylon Mesh
  66966. // NB : All CSG operations are performed in world coordinates
  66967. CSG.prototype.copyTransformAttributes = function (csg) {
  66968. this.matrix = csg.matrix;
  66969. this.position = csg.position;
  66970. this.rotation = csg.rotation;
  66971. this.scaling = csg.scaling;
  66972. this.rotationQuaternion = csg.rotationQuaternion;
  66973. return this;
  66974. };
  66975. // Build Raw mesh from CSG
  66976. // Coordinates here are in world space
  66977. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  66978. var matrix = this.matrix.clone();
  66979. matrix.invert();
  66980. 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;
  66981. if (keepSubMeshes) {
  66982. // Sort Polygons, since subMeshes are indices range
  66983. polygons.sort(function (a, b) {
  66984. if (a.shared.meshId === b.shared.meshId) {
  66985. return a.shared.subMeshId - b.shared.subMeshId;
  66986. }
  66987. else {
  66988. return a.shared.meshId - b.shared.meshId;
  66989. }
  66990. });
  66991. }
  66992. for (var i = 0, il = polygons.length; i < il; i++) {
  66993. polygon = polygons[i];
  66994. // Building SubMeshes
  66995. if (!subMesh_dict[polygon.shared.meshId]) {
  66996. subMesh_dict[polygon.shared.meshId] = {};
  66997. }
  66998. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  66999. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  67000. indexStart: +Infinity,
  67001. indexEnd: -Infinity,
  67002. materialIndex: polygon.shared.materialIndex
  67003. };
  67004. }
  67005. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  67006. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  67007. polygonIndices[0] = 0;
  67008. polygonIndices[1] = j - 1;
  67009. polygonIndices[2] = j;
  67010. for (var k = 0; k < 3; k++) {
  67011. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  67012. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  67013. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  67014. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  67015. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  67016. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  67017. // Check if 2 points can be merged
  67018. if (!(typeof vertex_idx !== 'undefined' &&
  67019. normals[vertex_idx * 3] === localNormal.x &&
  67020. normals[vertex_idx * 3 + 1] === localNormal.y &&
  67021. normals[vertex_idx * 3 + 2] === localNormal.z &&
  67022. uvs[vertex_idx * 2] === uv.x &&
  67023. uvs[vertex_idx * 2 + 1] === uv.y)) {
  67024. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  67025. uvs.push(uv.x, uv.y);
  67026. normals.push(normal.x, normal.y, normal.z);
  67027. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  67028. }
  67029. indices.push(vertex_idx);
  67030. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  67031. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  67032. currentIndex++;
  67033. }
  67034. }
  67035. }
  67036. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  67037. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  67038. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  67039. mesh.setIndices(indices, null);
  67040. if (keepSubMeshes) {
  67041. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  67042. var materialIndexOffset = 0, materialMaxIndex;
  67043. mesh.subMeshes = new Array();
  67044. for (var m in subMesh_dict) {
  67045. materialMaxIndex = -1;
  67046. for (var sm in subMesh_dict[m]) {
  67047. subMesh_obj = subMesh_dict[m][sm];
  67048. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  67049. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  67050. }
  67051. materialIndexOffset += ++materialMaxIndex;
  67052. }
  67053. }
  67054. return mesh;
  67055. };
  67056. // Build Mesh from CSG taking material and transforms into account
  67057. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  67058. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  67059. mesh.material = material;
  67060. mesh.position.copyFrom(this.position);
  67061. mesh.rotation.copyFrom(this.rotation);
  67062. if (this.rotationQuaternion) {
  67063. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  67064. }
  67065. mesh.scaling.copyFrom(this.scaling);
  67066. mesh.computeWorldMatrix(true);
  67067. return mesh;
  67068. };
  67069. return CSG;
  67070. }());
  67071. BABYLON.CSG = CSG;
  67072. })(BABYLON || (BABYLON = {}));
  67073. //# sourceMappingURL=babylon.csg.js.map
  67074. var BABYLON;
  67075. (function (BABYLON) {
  67076. var LensFlare = /** @class */ (function () {
  67077. function LensFlare(size, position, color, imgUrl, system) {
  67078. this.size = size;
  67079. this.position = position;
  67080. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  67081. this.color = color || new BABYLON.Color3(1, 1, 1);
  67082. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  67083. this._system = system;
  67084. system.lensFlares.push(this);
  67085. }
  67086. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  67087. return new LensFlare(size, position, color, imgUrl, system);
  67088. };
  67089. LensFlare.prototype.dispose = function () {
  67090. if (this.texture) {
  67091. this.texture.dispose();
  67092. }
  67093. // Remove from scene
  67094. var index = this._system.lensFlares.indexOf(this);
  67095. this._system.lensFlares.splice(index, 1);
  67096. };
  67097. ;
  67098. return LensFlare;
  67099. }());
  67100. BABYLON.LensFlare = LensFlare;
  67101. })(BABYLON || (BABYLON = {}));
  67102. //# sourceMappingURL=babylon.lensFlare.js.map
  67103. var BABYLON;
  67104. (function (BABYLON) {
  67105. var LensFlareSystem = /** @class */ (function () {
  67106. function LensFlareSystem(name, emitter, scene) {
  67107. this.name = name;
  67108. this.lensFlares = new Array();
  67109. this.borderLimit = 300;
  67110. this.viewportBorder = 0;
  67111. this.layerMask = 0x0FFFFFFF;
  67112. this._vertexBuffers = {};
  67113. this._isEnabled = true;
  67114. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  67115. this._emitter = emitter;
  67116. this.id = name;
  67117. scene.lensFlareSystems.push(this);
  67118. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  67119. var engine = scene.getEngine();
  67120. // VBO
  67121. var vertices = [];
  67122. vertices.push(1, 1);
  67123. vertices.push(-1, 1);
  67124. vertices.push(-1, -1);
  67125. vertices.push(1, -1);
  67126. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  67127. // Indices
  67128. var indices = [];
  67129. indices.push(0);
  67130. indices.push(1);
  67131. indices.push(2);
  67132. indices.push(0);
  67133. indices.push(2);
  67134. indices.push(3);
  67135. this._indexBuffer = engine.createIndexBuffer(indices);
  67136. // Effects
  67137. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  67138. }
  67139. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  67140. get: function () {
  67141. return this._isEnabled;
  67142. },
  67143. set: function (value) {
  67144. this._isEnabled = value;
  67145. },
  67146. enumerable: true,
  67147. configurable: true
  67148. });
  67149. LensFlareSystem.prototype.getScene = function () {
  67150. return this._scene;
  67151. };
  67152. LensFlareSystem.prototype.getEmitter = function () {
  67153. return this._emitter;
  67154. };
  67155. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  67156. this._emitter = newEmitter;
  67157. };
  67158. LensFlareSystem.prototype.getEmitterPosition = function () {
  67159. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  67160. };
  67161. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  67162. var position = this.getEmitterPosition();
  67163. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  67164. this._positionX = position.x;
  67165. this._positionY = position.y;
  67166. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  67167. if (this.viewportBorder > 0) {
  67168. globalViewport.x -= this.viewportBorder;
  67169. globalViewport.y -= this.viewportBorder;
  67170. globalViewport.width += this.viewportBorder * 2;
  67171. globalViewport.height += this.viewportBorder * 2;
  67172. position.x += this.viewportBorder;
  67173. position.y += this.viewportBorder;
  67174. this._positionX += this.viewportBorder;
  67175. this._positionY += this.viewportBorder;
  67176. }
  67177. if (position.z > 0) {
  67178. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  67179. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  67180. return true;
  67181. }
  67182. return true;
  67183. }
  67184. return false;
  67185. };
  67186. LensFlareSystem.prototype._isVisible = function () {
  67187. if (!this._isEnabled || !this._scene.activeCamera) {
  67188. return false;
  67189. }
  67190. var emitterPosition = this.getEmitterPosition();
  67191. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  67192. var distance = direction.length();
  67193. direction.normalize();
  67194. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  67195. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  67196. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  67197. };
  67198. LensFlareSystem.prototype.render = function () {
  67199. if (!this._effect.isReady() || !this._scene.activeCamera)
  67200. return false;
  67201. var engine = this._scene.getEngine();
  67202. var viewport = this._scene.activeCamera.viewport;
  67203. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  67204. // Position
  67205. if (!this.computeEffectivePosition(globalViewport)) {
  67206. return false;
  67207. }
  67208. // Visibility
  67209. if (!this._isVisible()) {
  67210. return false;
  67211. }
  67212. // Intensity
  67213. var awayX;
  67214. var awayY;
  67215. if (this._positionX < this.borderLimit + globalViewport.x) {
  67216. awayX = this.borderLimit + globalViewport.x - this._positionX;
  67217. }
  67218. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  67219. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  67220. }
  67221. else {
  67222. awayX = 0;
  67223. }
  67224. if (this._positionY < this.borderLimit + globalViewport.y) {
  67225. awayY = this.borderLimit + globalViewport.y - this._positionY;
  67226. }
  67227. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  67228. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  67229. }
  67230. else {
  67231. awayY = 0;
  67232. }
  67233. var away = (awayX > awayY) ? awayX : awayY;
  67234. away -= this.viewportBorder;
  67235. if (away > this.borderLimit) {
  67236. away = this.borderLimit;
  67237. }
  67238. var intensity = 1.0 - (away / this.borderLimit);
  67239. if (intensity < 0) {
  67240. return false;
  67241. }
  67242. if (intensity > 1.0) {
  67243. intensity = 1.0;
  67244. }
  67245. if (this.viewportBorder > 0) {
  67246. globalViewport.x += this.viewportBorder;
  67247. globalViewport.y += this.viewportBorder;
  67248. globalViewport.width -= this.viewportBorder * 2;
  67249. globalViewport.height -= this.viewportBorder * 2;
  67250. this._positionX -= this.viewportBorder;
  67251. this._positionY -= this.viewportBorder;
  67252. }
  67253. // Position
  67254. var centerX = globalViewport.x + globalViewport.width / 2;
  67255. var centerY = globalViewport.y + globalViewport.height / 2;
  67256. var distX = centerX - this._positionX;
  67257. var distY = centerY - this._positionY;
  67258. // Effects
  67259. engine.enableEffect(this._effect);
  67260. engine.setState(false);
  67261. engine.setDepthBuffer(false);
  67262. // VBOs
  67263. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  67264. // Flares
  67265. for (var index = 0; index < this.lensFlares.length; index++) {
  67266. var flare = this.lensFlares[index];
  67267. engine.setAlphaMode(flare.alphaMode);
  67268. var x = centerX - (distX * flare.position);
  67269. var y = centerY - (distY * flare.position);
  67270. var cw = flare.size;
  67271. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  67272. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  67273. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  67274. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  67275. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  67276. // Texture
  67277. this._effect.setTexture("textureSampler", flare.texture);
  67278. // Color
  67279. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  67280. // Draw order
  67281. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  67282. }
  67283. engine.setDepthBuffer(true);
  67284. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  67285. return true;
  67286. };
  67287. LensFlareSystem.prototype.dispose = function () {
  67288. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  67289. if (vertexBuffer) {
  67290. vertexBuffer.dispose();
  67291. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  67292. }
  67293. if (this._indexBuffer) {
  67294. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  67295. this._indexBuffer = null;
  67296. }
  67297. while (this.lensFlares.length) {
  67298. this.lensFlares[0].dispose();
  67299. }
  67300. // Remove from scene
  67301. var index = this._scene.lensFlareSystems.indexOf(this);
  67302. this._scene.lensFlareSystems.splice(index, 1);
  67303. };
  67304. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  67305. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  67306. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  67307. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  67308. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  67309. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  67310. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  67311. var parsedFlare = parsedLensFlareSystem.flares[index];
  67312. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  67313. }
  67314. return lensFlareSystem;
  67315. };
  67316. LensFlareSystem.prototype.serialize = function () {
  67317. var serializationObject = {};
  67318. serializationObject.id = this.id;
  67319. serializationObject.name = this.name;
  67320. serializationObject.emitterId = this.getEmitter().id;
  67321. serializationObject.borderLimit = this.borderLimit;
  67322. serializationObject.flares = [];
  67323. for (var index = 0; index < this.lensFlares.length; index++) {
  67324. var flare = this.lensFlares[index];
  67325. serializationObject.flares.push({
  67326. size: flare.size,
  67327. position: flare.position,
  67328. color: flare.color.asArray(),
  67329. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  67330. });
  67331. }
  67332. return serializationObject;
  67333. };
  67334. return LensFlareSystem;
  67335. }());
  67336. BABYLON.LensFlareSystem = LensFlareSystem;
  67337. })(BABYLON || (BABYLON = {}));
  67338. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  67339. var BABYLON;
  67340. (function (BABYLON) {
  67341. /**
  67342. * This is a holder class for the physics joint created by the physics plugin.
  67343. * It holds a set of functions to control the underlying joint.
  67344. */
  67345. var PhysicsJoint = /** @class */ (function () {
  67346. function PhysicsJoint(type, jointData) {
  67347. this.type = type;
  67348. this.jointData = jointData;
  67349. jointData.nativeParams = jointData.nativeParams || {};
  67350. }
  67351. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  67352. get: function () {
  67353. return this._physicsJoint;
  67354. },
  67355. set: function (newJoint) {
  67356. if (this._physicsJoint) {
  67357. //remove from the wolrd
  67358. }
  67359. this._physicsJoint = newJoint;
  67360. },
  67361. enumerable: true,
  67362. configurable: true
  67363. });
  67364. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  67365. set: function (physicsPlugin) {
  67366. this._physicsPlugin = physicsPlugin;
  67367. },
  67368. enumerable: true,
  67369. configurable: true
  67370. });
  67371. /**
  67372. * Execute a function that is physics-plugin specific.
  67373. * @param {Function} func the function that will be executed.
  67374. * It accepts two parameters: the physics world and the physics joint.
  67375. */
  67376. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  67377. func(this._physicsPlugin.world, this._physicsJoint);
  67378. };
  67379. //TODO check if the native joints are the same
  67380. //Joint Types
  67381. PhysicsJoint.DistanceJoint = 0;
  67382. PhysicsJoint.HingeJoint = 1;
  67383. PhysicsJoint.BallAndSocketJoint = 2;
  67384. PhysicsJoint.WheelJoint = 3;
  67385. PhysicsJoint.SliderJoint = 4;
  67386. //OIMO
  67387. PhysicsJoint.PrismaticJoint = 5;
  67388. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  67389. PhysicsJoint.UniversalJoint = 6;
  67390. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  67391. //Cannon
  67392. //Similar to a Ball-Joint. Different in params
  67393. PhysicsJoint.PointToPointJoint = 8;
  67394. //Cannon only at the moment
  67395. PhysicsJoint.SpringJoint = 9;
  67396. PhysicsJoint.LockJoint = 10;
  67397. return PhysicsJoint;
  67398. }());
  67399. BABYLON.PhysicsJoint = PhysicsJoint;
  67400. /**
  67401. * A class representing a physics distance joint.
  67402. */
  67403. var DistanceJoint = /** @class */ (function (_super) {
  67404. __extends(DistanceJoint, _super);
  67405. function DistanceJoint(jointData) {
  67406. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  67407. }
  67408. /**
  67409. * Update the predefined distance.
  67410. */
  67411. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  67412. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  67413. };
  67414. return DistanceJoint;
  67415. }(PhysicsJoint));
  67416. BABYLON.DistanceJoint = DistanceJoint;
  67417. var MotorEnabledJoint = /** @class */ (function (_super) {
  67418. __extends(MotorEnabledJoint, _super);
  67419. function MotorEnabledJoint(type, jointData) {
  67420. return _super.call(this, type, jointData) || this;
  67421. }
  67422. /**
  67423. * Set the motor values.
  67424. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67425. * @param {number} force the force to apply
  67426. * @param {number} maxForce max force for this motor.
  67427. */
  67428. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  67429. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  67430. };
  67431. /**
  67432. * Set the motor's limits.
  67433. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67434. */
  67435. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  67436. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  67437. };
  67438. return MotorEnabledJoint;
  67439. }(PhysicsJoint));
  67440. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  67441. /**
  67442. * This class represents a single hinge physics joint
  67443. */
  67444. var HingeJoint = /** @class */ (function (_super) {
  67445. __extends(HingeJoint, _super);
  67446. function HingeJoint(jointData) {
  67447. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  67448. }
  67449. /**
  67450. * Set the motor values.
  67451. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67452. * @param {number} force the force to apply
  67453. * @param {number} maxForce max force for this motor.
  67454. */
  67455. HingeJoint.prototype.setMotor = function (force, maxForce) {
  67456. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  67457. };
  67458. /**
  67459. * Set the motor's limits.
  67460. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67461. */
  67462. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  67463. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  67464. };
  67465. return HingeJoint;
  67466. }(MotorEnabledJoint));
  67467. BABYLON.HingeJoint = HingeJoint;
  67468. /**
  67469. * This class represents a dual hinge physics joint (same as wheel joint)
  67470. */
  67471. var Hinge2Joint = /** @class */ (function (_super) {
  67472. __extends(Hinge2Joint, _super);
  67473. function Hinge2Joint(jointData) {
  67474. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  67475. }
  67476. /**
  67477. * Set the motor values.
  67478. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67479. * @param {number} force the force to apply
  67480. * @param {number} maxForce max force for this motor.
  67481. * @param {motorIndex} the motor's index, 0 or 1.
  67482. */
  67483. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  67484. if (motorIndex === void 0) { motorIndex = 0; }
  67485. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  67486. };
  67487. /**
  67488. * Set the motor limits.
  67489. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67490. * @param {number} upperLimit the upper limit
  67491. * @param {number} lowerLimit lower limit
  67492. * @param {motorIndex} the motor's index, 0 or 1.
  67493. */
  67494. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  67495. if (motorIndex === void 0) { motorIndex = 0; }
  67496. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  67497. };
  67498. return Hinge2Joint;
  67499. }(MotorEnabledJoint));
  67500. BABYLON.Hinge2Joint = Hinge2Joint;
  67501. })(BABYLON || (BABYLON = {}));
  67502. //# sourceMappingURL=babylon.physicsJoint.js.map
  67503. var BABYLON;
  67504. (function (BABYLON) {
  67505. var PhysicsImpostor = /** @class */ (function () {
  67506. function PhysicsImpostor(object, type, _options, _scene) {
  67507. if (_options === void 0) { _options = { mass: 0 }; }
  67508. var _this = this;
  67509. this.object = object;
  67510. this.type = type;
  67511. this._options = _options;
  67512. this._scene = _scene;
  67513. this._bodyUpdateRequired = false;
  67514. this._onBeforePhysicsStepCallbacks = new Array();
  67515. this._onAfterPhysicsStepCallbacks = new Array();
  67516. this._onPhysicsCollideCallbacks = [];
  67517. this._deltaPosition = BABYLON.Vector3.Zero();
  67518. this._isDisposed = false;
  67519. //temp variables for parent rotation calculations
  67520. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  67521. this._tmpQuat = new BABYLON.Quaternion();
  67522. this._tmpQuat2 = new BABYLON.Quaternion();
  67523. /**
  67524. * this function is executed by the physics engine.
  67525. */
  67526. this.beforeStep = function () {
  67527. if (!_this._physicsEngine) {
  67528. return;
  67529. }
  67530. _this.object.translate(_this._deltaPosition, -1);
  67531. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  67532. _this.object.computeWorldMatrix(false);
  67533. if (_this.object.parent && _this.object.rotationQuaternion) {
  67534. _this.getParentsRotation();
  67535. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  67536. }
  67537. else {
  67538. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  67539. }
  67540. if (!_this._options.disableBidirectionalTransformation) {
  67541. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  67542. }
  67543. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  67544. func(_this);
  67545. });
  67546. };
  67547. /**
  67548. * this function is executed by the physics engine.
  67549. */
  67550. this.afterStep = function () {
  67551. if (!_this._physicsEngine) {
  67552. return;
  67553. }
  67554. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  67555. func(_this);
  67556. });
  67557. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  67558. // object has now its world rotation. needs to be converted to local.
  67559. if (_this.object.parent && _this.object.rotationQuaternion) {
  67560. _this.getParentsRotation();
  67561. _this._tmpQuat.conjugateInPlace();
  67562. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  67563. }
  67564. // take the position set and make it the absolute position of this object.
  67565. _this.object.setAbsolutePosition(_this.object.position);
  67566. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  67567. _this.object.translate(_this._deltaPosition, 1);
  67568. };
  67569. /**
  67570. * Legacy collision detection event support
  67571. */
  67572. this.onCollideEvent = null;
  67573. //event and body object due to cannon's event-based architecture.
  67574. this.onCollide = function (e) {
  67575. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  67576. return;
  67577. }
  67578. if (!_this._physicsEngine) {
  67579. return;
  67580. }
  67581. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  67582. if (otherImpostor) {
  67583. // Legacy collision detection event support
  67584. if (_this.onCollideEvent) {
  67585. _this.onCollideEvent(_this, otherImpostor);
  67586. }
  67587. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  67588. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  67589. }).forEach(function (obj) {
  67590. obj.callback(_this, otherImpostor);
  67591. });
  67592. }
  67593. };
  67594. //sanity check!
  67595. if (!this.object) {
  67596. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  67597. return;
  67598. }
  67599. //legacy support for old syntax.
  67600. if (!this._scene && object.getScene) {
  67601. this._scene = object.getScene();
  67602. }
  67603. if (!this._scene) {
  67604. return;
  67605. }
  67606. this._physicsEngine = this._scene.getPhysicsEngine();
  67607. if (!this._physicsEngine) {
  67608. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  67609. }
  67610. else {
  67611. //set the object's quaternion, if not set
  67612. if (!this.object.rotationQuaternion) {
  67613. if (this.object.rotation) {
  67614. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  67615. }
  67616. else {
  67617. this.object.rotationQuaternion = new BABYLON.Quaternion();
  67618. }
  67619. }
  67620. //default options params
  67621. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  67622. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  67623. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  67624. this._joints = [];
  67625. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  67626. if (!this.object.parent || this._options.ignoreParent) {
  67627. this._init();
  67628. }
  67629. else if (this.object.parent.physicsImpostor) {
  67630. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  67631. }
  67632. }
  67633. }
  67634. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  67635. get: function () {
  67636. return this._isDisposed;
  67637. },
  67638. enumerable: true,
  67639. configurable: true
  67640. });
  67641. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  67642. get: function () {
  67643. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  67644. },
  67645. set: function (value) {
  67646. this.setMass(value);
  67647. },
  67648. enumerable: true,
  67649. configurable: true
  67650. });
  67651. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  67652. get: function () {
  67653. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  67654. },
  67655. set: function (value) {
  67656. if (!this._physicsEngine) {
  67657. return;
  67658. }
  67659. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  67660. },
  67661. enumerable: true,
  67662. configurable: true
  67663. });
  67664. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  67665. get: function () {
  67666. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  67667. },
  67668. set: function (value) {
  67669. if (!this._physicsEngine) {
  67670. return;
  67671. }
  67672. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  67673. },
  67674. enumerable: true,
  67675. configurable: true
  67676. });
  67677. /**
  67678. * This function will completly initialize this impostor.
  67679. * It will create a new body - but only if this mesh has no parent.
  67680. * If it has, this impostor will not be used other than to define the impostor
  67681. * of the child mesh.
  67682. */
  67683. PhysicsImpostor.prototype._init = function () {
  67684. if (!this._physicsEngine) {
  67685. return;
  67686. }
  67687. this._physicsEngine.removeImpostor(this);
  67688. this.physicsBody = null;
  67689. this._parent = this._parent || this._getPhysicsParent();
  67690. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  67691. this._physicsEngine.addImpostor(this);
  67692. }
  67693. };
  67694. PhysicsImpostor.prototype._getPhysicsParent = function () {
  67695. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  67696. var parentMesh = this.object.parent;
  67697. return parentMesh.physicsImpostor;
  67698. }
  67699. return null;
  67700. };
  67701. /**
  67702. * Should a new body be generated.
  67703. */
  67704. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  67705. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  67706. };
  67707. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  67708. this.forceUpdate();
  67709. };
  67710. /**
  67711. * Force a regeneration of this or the parent's impostor's body.
  67712. * Use under cautious - This will remove all joints already implemented.
  67713. */
  67714. PhysicsImpostor.prototype.forceUpdate = function () {
  67715. this._init();
  67716. if (this.parent && !this._options.ignoreParent) {
  67717. this.parent.forceUpdate();
  67718. }
  67719. };
  67720. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  67721. /*public get mesh(): AbstractMesh {
  67722. return this._mesh;
  67723. }*/
  67724. /**
  67725. * Gets the body that holds this impostor. Either its own, or its parent.
  67726. */
  67727. get: function () {
  67728. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  67729. },
  67730. /**
  67731. * Set the physics body. Used mainly by the physics engine/plugin
  67732. */
  67733. set: function (physicsBody) {
  67734. if (this._physicsBody && this._physicsEngine) {
  67735. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  67736. }
  67737. this._physicsBody = physicsBody;
  67738. this.resetUpdateFlags();
  67739. },
  67740. enumerable: true,
  67741. configurable: true
  67742. });
  67743. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  67744. get: function () {
  67745. return !this._options.ignoreParent && this._parent ? this._parent : null;
  67746. },
  67747. set: function (value) {
  67748. this._parent = value;
  67749. },
  67750. enumerable: true,
  67751. configurable: true
  67752. });
  67753. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  67754. this._bodyUpdateRequired = false;
  67755. };
  67756. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  67757. if (this.object.getBoundingInfo) {
  67758. var q = this.object.rotationQuaternion;
  67759. //reset rotation
  67760. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  67761. //calculate the world matrix with no rotation
  67762. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  67763. var boundingInfo = this.object.getBoundingInfo();
  67764. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  67765. //bring back the rotation
  67766. this.object.rotationQuaternion = q;
  67767. //calculate the world matrix with the new rotation
  67768. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  67769. return size;
  67770. }
  67771. else {
  67772. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  67773. }
  67774. };
  67775. PhysicsImpostor.prototype.getObjectCenter = function () {
  67776. if (this.object.getBoundingInfo) {
  67777. var boundingInfo = this.object.getBoundingInfo();
  67778. return boundingInfo.boundingBox.centerWorld;
  67779. }
  67780. else {
  67781. return this.object.position;
  67782. }
  67783. };
  67784. /**
  67785. * Get a specific parametes from the options parameter.
  67786. */
  67787. PhysicsImpostor.prototype.getParam = function (paramName) {
  67788. return this._options[paramName];
  67789. };
  67790. /**
  67791. * Sets a specific parameter in the options given to the physics plugin
  67792. */
  67793. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  67794. this._options[paramName] = value;
  67795. this._bodyUpdateRequired = true;
  67796. };
  67797. /**
  67798. * Specifically change the body's mass option. Won't recreate the physics body object
  67799. */
  67800. PhysicsImpostor.prototype.setMass = function (mass) {
  67801. if (this.getParam("mass") !== mass) {
  67802. this.setParam("mass", mass);
  67803. }
  67804. if (this._physicsEngine) {
  67805. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  67806. }
  67807. };
  67808. PhysicsImpostor.prototype.getLinearVelocity = function () {
  67809. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  67810. };
  67811. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  67812. if (this._physicsEngine) {
  67813. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  67814. }
  67815. };
  67816. PhysicsImpostor.prototype.getAngularVelocity = function () {
  67817. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  67818. };
  67819. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  67820. if (this._physicsEngine) {
  67821. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  67822. }
  67823. };
  67824. /**
  67825. * Execute a function with the physics plugin native code.
  67826. * Provide a function the will have two variables - the world object and the physics body object.
  67827. */
  67828. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  67829. if (this._physicsEngine) {
  67830. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  67831. }
  67832. };
  67833. /**
  67834. * Register a function that will be executed before the physics world is stepping forward.
  67835. */
  67836. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  67837. this._onBeforePhysicsStepCallbacks.push(func);
  67838. };
  67839. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  67840. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  67841. if (index > -1) {
  67842. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  67843. }
  67844. else {
  67845. BABYLON.Tools.Warn("Function to remove was not found");
  67846. }
  67847. };
  67848. /**
  67849. * Register a function that will be executed after the physics step
  67850. */
  67851. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  67852. this._onAfterPhysicsStepCallbacks.push(func);
  67853. };
  67854. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  67855. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  67856. if (index > -1) {
  67857. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  67858. }
  67859. else {
  67860. BABYLON.Tools.Warn("Function to remove was not found");
  67861. }
  67862. };
  67863. /**
  67864. * register a function that will be executed when this impostor collides against a different body.
  67865. */
  67866. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  67867. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  67868. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  67869. };
  67870. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  67871. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  67872. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  67873. if (index > -1) {
  67874. this._onPhysicsCollideCallbacks.splice(index, 1);
  67875. }
  67876. else {
  67877. BABYLON.Tools.Warn("Function to remove was not found");
  67878. }
  67879. };
  67880. PhysicsImpostor.prototype.getParentsRotation = function () {
  67881. var parent = this.object.parent;
  67882. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  67883. while (parent) {
  67884. if (parent.rotationQuaternion) {
  67885. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  67886. }
  67887. else {
  67888. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  67889. }
  67890. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  67891. parent = parent.parent;
  67892. }
  67893. return this._tmpQuat;
  67894. };
  67895. /**
  67896. * Apply a force
  67897. */
  67898. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  67899. if (this._physicsEngine) {
  67900. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  67901. }
  67902. return this;
  67903. };
  67904. /**
  67905. * Apply an impulse
  67906. */
  67907. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  67908. if (this._physicsEngine) {
  67909. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  67910. }
  67911. return this;
  67912. };
  67913. /**
  67914. * A help function to create a joint.
  67915. */
  67916. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  67917. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  67918. this.addJoint(otherImpostor, joint);
  67919. return this;
  67920. };
  67921. /**
  67922. * Add a joint to this impostor with a different impostor.
  67923. */
  67924. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  67925. this._joints.push({
  67926. otherImpostor: otherImpostor,
  67927. joint: joint
  67928. });
  67929. if (this._physicsEngine) {
  67930. this._physicsEngine.addJoint(this, otherImpostor, joint);
  67931. }
  67932. return this;
  67933. };
  67934. /**
  67935. * Will keep this body still, in a sleep mode.
  67936. */
  67937. PhysicsImpostor.prototype.sleep = function () {
  67938. if (this._physicsEngine) {
  67939. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  67940. }
  67941. return this;
  67942. };
  67943. /**
  67944. * Wake the body up.
  67945. */
  67946. PhysicsImpostor.prototype.wakeUp = function () {
  67947. if (this._physicsEngine) {
  67948. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  67949. }
  67950. return this;
  67951. };
  67952. PhysicsImpostor.prototype.clone = function (newObject) {
  67953. if (!newObject)
  67954. return null;
  67955. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  67956. };
  67957. PhysicsImpostor.prototype.dispose = function () {
  67958. var _this = this;
  67959. //no dispose if no physics engine is available.
  67960. if (!this._physicsEngine) {
  67961. return;
  67962. }
  67963. this._joints.forEach(function (j) {
  67964. if (_this._physicsEngine) {
  67965. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  67966. }
  67967. });
  67968. //dispose the physics body
  67969. this._physicsEngine.removeImpostor(this);
  67970. if (this.parent) {
  67971. this.parent.forceUpdate();
  67972. }
  67973. else {
  67974. /*this._object.getChildMeshes().forEach(function(mesh) {
  67975. if (mesh.physicsImpostor) {
  67976. if (disposeChildren) {
  67977. mesh.physicsImpostor.dispose();
  67978. mesh.physicsImpostor = null;
  67979. }
  67980. }
  67981. })*/
  67982. }
  67983. this._isDisposed = true;
  67984. };
  67985. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  67986. this._deltaPosition.copyFrom(position);
  67987. };
  67988. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  67989. if (!this._deltaRotation) {
  67990. this._deltaRotation = new BABYLON.Quaternion();
  67991. }
  67992. this._deltaRotation.copyFrom(rotation);
  67993. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  67994. };
  67995. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  67996. if (this._physicsEngine) {
  67997. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  67998. }
  67999. return this;
  68000. };
  68001. PhysicsImpostor.prototype.getRadius = function () {
  68002. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  68003. };
  68004. /**
  68005. * Sync a bone with this impostor
  68006. * @param bone The bone to sync to the impostor.
  68007. * @param boneMesh The mesh that the bone is influencing.
  68008. * @param jointPivot The pivot of the joint / bone in local space.
  68009. * @param distToJoint Optional distance from the impostor to the joint.
  68010. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  68011. */
  68012. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  68013. var tempVec = PhysicsImpostor._tmpVecs[0];
  68014. var mesh = this.object;
  68015. if (mesh.rotationQuaternion) {
  68016. if (adjustRotation) {
  68017. var tempQuat = PhysicsImpostor._tmpQuat;
  68018. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  68019. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  68020. }
  68021. else {
  68022. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  68023. }
  68024. }
  68025. tempVec.x = 0;
  68026. tempVec.y = 0;
  68027. tempVec.z = 0;
  68028. if (jointPivot) {
  68029. tempVec.x = jointPivot.x;
  68030. tempVec.y = jointPivot.y;
  68031. tempVec.z = jointPivot.z;
  68032. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  68033. if (distToJoint === undefined || distToJoint === null) {
  68034. distToJoint = jointPivot.length();
  68035. }
  68036. tempVec.x *= distToJoint;
  68037. tempVec.y *= distToJoint;
  68038. tempVec.z *= distToJoint;
  68039. }
  68040. if (bone.getParent()) {
  68041. tempVec.addInPlace(mesh.getAbsolutePosition());
  68042. bone.setAbsolutePosition(tempVec, boneMesh);
  68043. }
  68044. else {
  68045. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  68046. boneMesh.position.x -= tempVec.x;
  68047. boneMesh.position.y -= tempVec.y;
  68048. boneMesh.position.z -= tempVec.z;
  68049. }
  68050. };
  68051. /**
  68052. * Sync impostor to a bone
  68053. * @param bone The bone that the impostor will be synced to.
  68054. * @param boneMesh The mesh that the bone is influencing.
  68055. * @param jointPivot The pivot of the joint / bone in local space.
  68056. * @param distToJoint Optional distance from the impostor to the joint.
  68057. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  68058. * @param boneAxis Optional vector3 axis the bone is aligned with
  68059. */
  68060. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  68061. var mesh = this.object;
  68062. if (mesh.rotationQuaternion) {
  68063. if (adjustRotation) {
  68064. var tempQuat = PhysicsImpostor._tmpQuat;
  68065. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  68066. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  68067. }
  68068. else {
  68069. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  68070. }
  68071. }
  68072. var pos = PhysicsImpostor._tmpVecs[0];
  68073. var boneDir = PhysicsImpostor._tmpVecs[1];
  68074. if (!boneAxis) {
  68075. boneAxis = PhysicsImpostor._tmpVecs[2];
  68076. boneAxis.x = 0;
  68077. boneAxis.y = 1;
  68078. boneAxis.z = 0;
  68079. }
  68080. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  68081. bone.getAbsolutePositionToRef(boneMesh, pos);
  68082. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  68083. distToJoint = jointPivot.length();
  68084. }
  68085. if (distToJoint !== undefined && distToJoint !== null) {
  68086. pos.x += boneDir.x * distToJoint;
  68087. pos.y += boneDir.y * distToJoint;
  68088. pos.z += boneDir.z * distToJoint;
  68089. }
  68090. mesh.setAbsolutePosition(pos);
  68091. };
  68092. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  68093. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  68094. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  68095. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  68096. //Impostor types
  68097. PhysicsImpostor.NoImpostor = 0;
  68098. PhysicsImpostor.SphereImpostor = 1;
  68099. PhysicsImpostor.BoxImpostor = 2;
  68100. PhysicsImpostor.PlaneImpostor = 3;
  68101. PhysicsImpostor.MeshImpostor = 4;
  68102. PhysicsImpostor.CylinderImpostor = 7;
  68103. PhysicsImpostor.ParticleImpostor = 8;
  68104. PhysicsImpostor.HeightmapImpostor = 9;
  68105. return PhysicsImpostor;
  68106. }());
  68107. BABYLON.PhysicsImpostor = PhysicsImpostor;
  68108. })(BABYLON || (BABYLON = {}));
  68109. //# sourceMappingURL=babylon.physicsImpostor.js.map
  68110. var BABYLON;
  68111. (function (BABYLON) {
  68112. var PhysicsEngine = /** @class */ (function () {
  68113. function PhysicsEngine(gravity, _physicsPlugin) {
  68114. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  68115. this._physicsPlugin = _physicsPlugin;
  68116. //new methods and parameters
  68117. this._impostors = [];
  68118. this._joints = [];
  68119. if (!this._physicsPlugin.isSupported()) {
  68120. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  68121. + "Please make sure it is included.");
  68122. }
  68123. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  68124. this.setGravity(gravity);
  68125. this.setTimeStep();
  68126. }
  68127. PhysicsEngine.prototype.setGravity = function (gravity) {
  68128. this.gravity = gravity;
  68129. this._physicsPlugin.setGravity(this.gravity);
  68130. };
  68131. /**
  68132. * Set the time step of the physics engine.
  68133. * default is 1/60.
  68134. * To slow it down, enter 1/600 for example.
  68135. * To speed it up, 1/30
  68136. * @param {number} newTimeStep the new timestep to apply to this world.
  68137. */
  68138. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  68139. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  68140. this._physicsPlugin.setTimeStep(newTimeStep);
  68141. };
  68142. /**
  68143. * Get the time step of the physics engine.
  68144. */
  68145. PhysicsEngine.prototype.getTimeStep = function () {
  68146. return this._physicsPlugin.getTimeStep();
  68147. };
  68148. PhysicsEngine.prototype.dispose = function () {
  68149. this._impostors.forEach(function (impostor) {
  68150. impostor.dispose();
  68151. });
  68152. this._physicsPlugin.dispose();
  68153. };
  68154. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  68155. return this._physicsPlugin.name;
  68156. };
  68157. /**
  68158. * Adding a new impostor for the impostor tracking.
  68159. * This will be done by the impostor itself.
  68160. * @param {PhysicsImpostor} impostor the impostor to add
  68161. */
  68162. PhysicsEngine.prototype.addImpostor = function (impostor) {
  68163. impostor.uniqueId = this._impostors.push(impostor);
  68164. //if no parent, generate the body
  68165. if (!impostor.parent) {
  68166. this._physicsPlugin.generatePhysicsBody(impostor);
  68167. }
  68168. };
  68169. /**
  68170. * Remove an impostor from the engine.
  68171. * This impostor and its mesh will not longer be updated by the physics engine.
  68172. * @param {PhysicsImpostor} impostor the impostor to remove
  68173. */
  68174. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  68175. var index = this._impostors.indexOf(impostor);
  68176. if (index > -1) {
  68177. var removed = this._impostors.splice(index, 1);
  68178. //Is it needed?
  68179. if (removed.length) {
  68180. //this will also remove it from the world.
  68181. removed[0].physicsBody = null;
  68182. }
  68183. }
  68184. };
  68185. /**
  68186. * Add a joint to the physics engine
  68187. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  68188. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  68189. * @param {PhysicsJoint} the joint that will connect both impostors.
  68190. */
  68191. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  68192. var impostorJoint = {
  68193. mainImpostor: mainImpostor,
  68194. connectedImpostor: connectedImpostor,
  68195. joint: joint
  68196. };
  68197. joint.physicsPlugin = this._physicsPlugin;
  68198. this._joints.push(impostorJoint);
  68199. this._physicsPlugin.generateJoint(impostorJoint);
  68200. };
  68201. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  68202. var matchingJoints = this._joints.filter(function (impostorJoint) {
  68203. return (impostorJoint.connectedImpostor === connectedImpostor
  68204. && impostorJoint.joint === joint
  68205. && impostorJoint.mainImpostor === mainImpostor);
  68206. });
  68207. if (matchingJoints.length) {
  68208. this._physicsPlugin.removeJoint(matchingJoints[0]);
  68209. //TODO remove it from the list as well
  68210. }
  68211. };
  68212. /**
  68213. * Called by the scene. no need to call it.
  68214. */
  68215. PhysicsEngine.prototype._step = function (delta) {
  68216. var _this = this;
  68217. //check if any mesh has no body / requires an update
  68218. this._impostors.forEach(function (impostor) {
  68219. if (impostor.isBodyInitRequired()) {
  68220. _this._physicsPlugin.generatePhysicsBody(impostor);
  68221. }
  68222. });
  68223. if (delta > 0.1) {
  68224. delta = 0.1;
  68225. }
  68226. else if (delta <= 0) {
  68227. delta = 1.0 / 60.0;
  68228. }
  68229. this._physicsPlugin.executeStep(delta, this._impostors);
  68230. };
  68231. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  68232. return this._physicsPlugin;
  68233. };
  68234. PhysicsEngine.prototype.getImpostors = function () {
  68235. return this._impostors;
  68236. };
  68237. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  68238. for (var i = 0; i < this._impostors.length; ++i) {
  68239. if (this._impostors[i].object === object) {
  68240. return this._impostors[i];
  68241. }
  68242. }
  68243. return null;
  68244. };
  68245. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  68246. for (var i = 0; i < this._impostors.length; ++i) {
  68247. if (this._impostors[i].physicsBody === body) {
  68248. return this._impostors[i];
  68249. }
  68250. }
  68251. return null;
  68252. };
  68253. // Statics
  68254. PhysicsEngine.Epsilon = 0.001;
  68255. return PhysicsEngine;
  68256. }());
  68257. BABYLON.PhysicsEngine = PhysicsEngine;
  68258. })(BABYLON || (BABYLON = {}));
  68259. //# sourceMappingURL=babylon.physicsEngine.js.map
  68260. var BABYLON;
  68261. (function (BABYLON) {
  68262. var PhysicsHelper = /** @class */ (function () {
  68263. function PhysicsHelper(scene) {
  68264. this._scene = scene;
  68265. this._physicsEngine = this._scene.getPhysicsEngine();
  68266. if (!this._physicsEngine) {
  68267. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  68268. }
  68269. }
  68270. /**
  68271. * @param {Vector3} origin the origin of the explosion
  68272. * @param {number} radius the explosion radius
  68273. * @param {number} strength the explosion strength
  68274. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  68275. */
  68276. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  68277. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  68278. if (!this._physicsEngine) {
  68279. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  68280. return null;
  68281. }
  68282. var impostors = this._physicsEngine.getImpostors();
  68283. if (impostors.length === 0) {
  68284. return null;
  68285. }
  68286. var event = new PhysicsRadialExplosionEvent(this._scene);
  68287. impostors.forEach(function (impostor) {
  68288. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  68289. if (!impostorForceAndContactPoint) {
  68290. return;
  68291. }
  68292. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  68293. });
  68294. event.dispose(false);
  68295. return event;
  68296. };
  68297. /**
  68298. * @param {Vector3} origin the origin of the explosion
  68299. * @param {number} radius the explosion radius
  68300. * @param {number} strength the explosion strength
  68301. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  68302. */
  68303. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  68304. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  68305. if (!this._physicsEngine) {
  68306. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  68307. return null;
  68308. }
  68309. var impostors = this._physicsEngine.getImpostors();
  68310. if (impostors.length === 0) {
  68311. return null;
  68312. }
  68313. var event = new PhysicsRadialExplosionEvent(this._scene);
  68314. impostors.forEach(function (impostor) {
  68315. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  68316. if (!impostorForceAndContactPoint) {
  68317. return;
  68318. }
  68319. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  68320. });
  68321. event.dispose(false);
  68322. return event;
  68323. };
  68324. /**
  68325. * @param {Vector3} origin the origin of the explosion
  68326. * @param {number} radius the explosion radius
  68327. * @param {number} strength the explosion strength
  68328. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  68329. */
  68330. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  68331. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  68332. if (!this._physicsEngine) {
  68333. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  68334. return null;
  68335. }
  68336. var impostors = this._physicsEngine.getImpostors();
  68337. if (impostors.length === 0) {
  68338. return null;
  68339. }
  68340. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  68341. event.dispose(false);
  68342. return event;
  68343. };
  68344. /**
  68345. * @param {Vector3} origin the origin of the updraft
  68346. * @param {number} radius the radius of the updraft
  68347. * @param {number} strength the strength of the updraft
  68348. * @param {number} height the height of the updraft
  68349. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  68350. */
  68351. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  68352. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  68353. if (!this._physicsEngine) {
  68354. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  68355. return null;
  68356. }
  68357. if (this._physicsEngine.getImpostors().length === 0) {
  68358. return null;
  68359. }
  68360. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  68361. event.dispose(false);
  68362. return event;
  68363. };
  68364. /**
  68365. * @param {Vector3} origin the of the vortex
  68366. * @param {number} radius the radius of the vortex
  68367. * @param {number} strength the strength of the vortex
  68368. * @param {number} height the height of the vortex
  68369. */
  68370. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  68371. if (!this._physicsEngine) {
  68372. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  68373. return null;
  68374. }
  68375. if (this._physicsEngine.getImpostors().length === 0) {
  68376. return null;
  68377. }
  68378. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  68379. event.dispose(false);
  68380. return event;
  68381. };
  68382. return PhysicsHelper;
  68383. }());
  68384. BABYLON.PhysicsHelper = PhysicsHelper;
  68385. /***** Radial explosion *****/
  68386. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  68387. function PhysicsRadialExplosionEvent(scene) {
  68388. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  68389. this._rays = [];
  68390. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  68391. this._scene = scene;
  68392. }
  68393. /**
  68394. * Returns the data related to the radial explosion event (sphere & rays).
  68395. * @returns {PhysicsRadialExplosionEventData}
  68396. */
  68397. PhysicsRadialExplosionEvent.prototype.getData = function () {
  68398. this._dataFetched = true;
  68399. return {
  68400. sphere: this._sphere,
  68401. rays: this._rays,
  68402. };
  68403. };
  68404. /**
  68405. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  68406. * @param impostor
  68407. * @param {Vector3} origin the origin of the explosion
  68408. * @param {number} radius the explosion radius
  68409. * @param {number} strength the explosion strength
  68410. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  68411. * @returns {Nullable<PhysicsForceAndContactPoint>}
  68412. */
  68413. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  68414. if (impostor.mass === 0) {
  68415. return null;
  68416. }
  68417. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  68418. return null;
  68419. }
  68420. if (impostor.object.getClassName() !== 'Mesh') {
  68421. return null;
  68422. }
  68423. var impostorObject = impostor.object;
  68424. var impostorObjectCenter = impostor.getObjectCenter();
  68425. var direction = impostorObjectCenter.subtract(origin);
  68426. var ray = new BABYLON.Ray(origin, direction, radius);
  68427. this._rays.push(ray);
  68428. var hit = ray.intersectsMesh(impostorObject);
  68429. var contactPoint = hit.pickedPoint;
  68430. if (!contactPoint) {
  68431. return null;
  68432. }
  68433. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  68434. if (distanceFromOrigin > radius) {
  68435. return null;
  68436. }
  68437. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  68438. ? strength
  68439. : strength * (1 - (distanceFromOrigin / radius));
  68440. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  68441. return { force: force, contactPoint: contactPoint };
  68442. };
  68443. /**
  68444. * Disposes the sphere.
  68445. * @param {bolean} force
  68446. */
  68447. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  68448. var _this = this;
  68449. if (force === void 0) { force = true; }
  68450. if (force) {
  68451. this._sphere.dispose();
  68452. }
  68453. else {
  68454. setTimeout(function () {
  68455. if (!_this._dataFetched) {
  68456. _this._sphere.dispose();
  68457. }
  68458. }, 0);
  68459. }
  68460. };
  68461. /*** Helpers ***/
  68462. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  68463. if (!this._sphere) {
  68464. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  68465. this._sphere.isVisible = false;
  68466. }
  68467. };
  68468. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  68469. var impostorObject = impostor.object;
  68470. this._prepareSphere();
  68471. this._sphere.position = origin;
  68472. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  68473. this._sphere._updateBoundingInfo();
  68474. this._sphere.computeWorldMatrix(true);
  68475. return this._sphere.intersectsMesh(impostorObject, true);
  68476. };
  68477. return PhysicsRadialExplosionEvent;
  68478. }());
  68479. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  68480. /***** Gravitational Field *****/
  68481. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  68482. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  68483. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  68484. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  68485. this._physicsHelper = physicsHelper;
  68486. this._scene = scene;
  68487. this._origin = origin;
  68488. this._radius = radius;
  68489. this._strength = strength;
  68490. this._falloff = falloff;
  68491. this._tickCallback = this._tick.bind(this);
  68492. }
  68493. /**
  68494. * Returns the data related to the gravitational field event (sphere).
  68495. * @returns {PhysicsGravitationalFieldEventData}
  68496. */
  68497. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  68498. this._dataFetched = true;
  68499. return {
  68500. sphere: this._sphere,
  68501. };
  68502. };
  68503. /**
  68504. * Enables the gravitational field.
  68505. */
  68506. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  68507. this._tickCallback.call(this);
  68508. this._scene.registerBeforeRender(this._tickCallback);
  68509. };
  68510. /**
  68511. * Disables the gravitational field.
  68512. */
  68513. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  68514. this._scene.unregisterBeforeRender(this._tickCallback);
  68515. };
  68516. /**
  68517. * Disposes the sphere.
  68518. * @param {bolean} force
  68519. */
  68520. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  68521. var _this = this;
  68522. if (force === void 0) { force = true; }
  68523. if (force) {
  68524. this._sphere.dispose();
  68525. }
  68526. else {
  68527. setTimeout(function () {
  68528. if (!_this._dataFetched) {
  68529. _this._sphere.dispose();
  68530. }
  68531. }, 0);
  68532. }
  68533. };
  68534. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  68535. // Since the params won't change, we fetch the event only once
  68536. if (this._sphere) {
  68537. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  68538. }
  68539. else {
  68540. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  68541. if (radialExplosionEvent) {
  68542. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  68543. }
  68544. }
  68545. };
  68546. return PhysicsGravitationalFieldEvent;
  68547. }());
  68548. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  68549. /***** Updraft *****/
  68550. var PhysicsUpdraftEvent = /** @class */ (function () {
  68551. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  68552. this._scene = _scene;
  68553. this._origin = _origin;
  68554. this._radius = _radius;
  68555. this._strength = _strength;
  68556. this._height = _height;
  68557. this._updraftMode = _updraftMode;
  68558. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  68559. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  68560. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  68561. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  68562. this._physicsEngine = this._scene.getPhysicsEngine();
  68563. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  68564. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  68565. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  68566. this._originDirection = this._origin.subtract(this._originTop).normalize();
  68567. }
  68568. this._tickCallback = this._tick.bind(this);
  68569. }
  68570. /**
  68571. * Returns the data related to the updraft event (cylinder).
  68572. * @returns {PhysicsUpdraftEventData}
  68573. */
  68574. PhysicsUpdraftEvent.prototype.getData = function () {
  68575. this._dataFetched = true;
  68576. return {
  68577. cylinder: this._cylinder,
  68578. };
  68579. };
  68580. /**
  68581. * Enables the updraft.
  68582. */
  68583. PhysicsUpdraftEvent.prototype.enable = function () {
  68584. this._tickCallback.call(this);
  68585. this._scene.registerBeforeRender(this._tickCallback);
  68586. };
  68587. /**
  68588. * Disables the cortex.
  68589. */
  68590. PhysicsUpdraftEvent.prototype.disable = function () {
  68591. this._scene.unregisterBeforeRender(this._tickCallback);
  68592. };
  68593. /**
  68594. * Disposes the sphere.
  68595. * @param {bolean} force
  68596. */
  68597. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  68598. var _this = this;
  68599. if (force === void 0) { force = true; }
  68600. if (force) {
  68601. this._cylinder.dispose();
  68602. }
  68603. else {
  68604. setTimeout(function () {
  68605. if (!_this._dataFetched) {
  68606. _this._cylinder.dispose();
  68607. }
  68608. }, 0);
  68609. }
  68610. };
  68611. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  68612. if (impostor.mass === 0) {
  68613. return null;
  68614. }
  68615. if (!this._intersectsWithCylinder(impostor)) {
  68616. return null;
  68617. }
  68618. var impostorObjectCenter = impostor.getObjectCenter();
  68619. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  68620. var direction = this._originDirection;
  68621. }
  68622. else {
  68623. var direction = impostorObjectCenter.subtract(this._originTop);
  68624. }
  68625. var multiplier = this._strength * -1;
  68626. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  68627. return { force: force, contactPoint: impostorObjectCenter };
  68628. };
  68629. PhysicsUpdraftEvent.prototype._tick = function () {
  68630. var _this = this;
  68631. this._physicsEngine.getImpostors().forEach(function (impostor) {
  68632. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  68633. if (!impostorForceAndContactPoint) {
  68634. return;
  68635. }
  68636. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  68637. });
  68638. };
  68639. /*** Helpers ***/
  68640. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  68641. if (!this._cylinder) {
  68642. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  68643. height: this._height,
  68644. diameter: this._radius * 2,
  68645. }, this._scene);
  68646. this._cylinder.isVisible = false;
  68647. }
  68648. };
  68649. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  68650. var impostorObject = impostor.object;
  68651. this._prepareCylinder();
  68652. this._cylinder.position = this._cylinderPosition;
  68653. return this._cylinder.intersectsMesh(impostorObject, true);
  68654. };
  68655. return PhysicsUpdraftEvent;
  68656. }());
  68657. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  68658. /***** Vortex *****/
  68659. var PhysicsVortexEvent = /** @class */ (function () {
  68660. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  68661. this._scene = _scene;
  68662. this._origin = _origin;
  68663. this._radius = _radius;
  68664. this._strength = _strength;
  68665. this._height = _height;
  68666. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  68667. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  68668. this._updraftMultiplier = 0.02;
  68669. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  68670. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  68671. this._physicsEngine = this._scene.getPhysicsEngine();
  68672. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  68673. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  68674. this._tickCallback = this._tick.bind(this);
  68675. }
  68676. /**
  68677. * Returns the data related to the vortex event (cylinder).
  68678. * @returns {PhysicsVortexEventData}
  68679. */
  68680. PhysicsVortexEvent.prototype.getData = function () {
  68681. this._dataFetched = true;
  68682. return {
  68683. cylinder: this._cylinder,
  68684. };
  68685. };
  68686. /**
  68687. * Enables the vortex.
  68688. */
  68689. PhysicsVortexEvent.prototype.enable = function () {
  68690. this._tickCallback.call(this);
  68691. this._scene.registerBeforeRender(this._tickCallback);
  68692. };
  68693. /**
  68694. * Disables the cortex.
  68695. */
  68696. PhysicsVortexEvent.prototype.disable = function () {
  68697. this._scene.unregisterBeforeRender(this._tickCallback);
  68698. };
  68699. /**
  68700. * Disposes the sphere.
  68701. * @param {bolean} force
  68702. */
  68703. PhysicsVortexEvent.prototype.dispose = function (force) {
  68704. var _this = this;
  68705. if (force === void 0) { force = true; }
  68706. if (force) {
  68707. this._cylinder.dispose();
  68708. }
  68709. else {
  68710. setTimeout(function () {
  68711. if (!_this._dataFetched) {
  68712. _this._cylinder.dispose();
  68713. }
  68714. }, 0);
  68715. }
  68716. };
  68717. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  68718. if (impostor.mass === 0) {
  68719. return null;
  68720. }
  68721. if (!this._intersectsWithCylinder(impostor)) {
  68722. return null;
  68723. }
  68724. if (impostor.object.getClassName() !== 'Mesh') {
  68725. return null;
  68726. }
  68727. var impostorObject = impostor.object;
  68728. var impostorObjectCenter = impostor.getObjectCenter();
  68729. 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)
  68730. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  68731. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  68732. var hit = ray.intersectsMesh(impostorObject);
  68733. var contactPoint = hit.pickedPoint;
  68734. if (!contactPoint) {
  68735. return null;
  68736. }
  68737. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  68738. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  68739. var directionToOrigin = contactPoint.normalize();
  68740. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  68741. directionToOrigin = directionToOrigin.negate();
  68742. }
  68743. // TODO: find a more physically based solution
  68744. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  68745. var forceX = directionToOrigin.x * this._strength / 8;
  68746. var forceY = directionToOrigin.y * this._updraftMultiplier;
  68747. var forceZ = directionToOrigin.z * this._strength / 8;
  68748. }
  68749. else {
  68750. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  68751. var forceY = this._originTop.y * this._updraftMultiplier;
  68752. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  68753. }
  68754. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  68755. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  68756. return { force: force, contactPoint: impostorObjectCenter };
  68757. };
  68758. PhysicsVortexEvent.prototype._tick = function () {
  68759. var _this = this;
  68760. this._physicsEngine.getImpostors().forEach(function (impostor) {
  68761. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  68762. if (!impostorForceAndContactPoint) {
  68763. return;
  68764. }
  68765. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  68766. });
  68767. };
  68768. /*** Helpers ***/
  68769. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  68770. if (!this._cylinder) {
  68771. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  68772. height: this._height,
  68773. diameter: this._radius * 2,
  68774. }, this._scene);
  68775. this._cylinder.isVisible = false;
  68776. }
  68777. };
  68778. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  68779. var impostorObject = impostor.object;
  68780. this._prepareCylinder();
  68781. this._cylinder.position = this._cylinderPosition;
  68782. return this._cylinder.intersectsMesh(impostorObject, true);
  68783. };
  68784. return PhysicsVortexEvent;
  68785. }());
  68786. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  68787. /***** Enums *****/
  68788. /**
  68789. * The strenght of the force in correspondence to the distance of the affected object
  68790. */
  68791. var PhysicsRadialImpulseFalloff;
  68792. (function (PhysicsRadialImpulseFalloff) {
  68793. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  68794. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  68795. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  68796. /**
  68797. * The strenght of the force in correspondence to the distance of the affected object
  68798. */
  68799. var PhysicsUpdraftMode;
  68800. (function (PhysicsUpdraftMode) {
  68801. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  68802. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  68803. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  68804. })(BABYLON || (BABYLON = {}));
  68805. //# sourceMappingURL=babylon.physicsHelper.js.map
  68806. var BABYLON;
  68807. (function (BABYLON) {
  68808. var CannonJSPlugin = /** @class */ (function () {
  68809. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  68810. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  68811. if (iterations === void 0) { iterations = 10; }
  68812. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  68813. this.name = "CannonJSPlugin";
  68814. this._physicsMaterials = new Array();
  68815. this._fixedTimeStep = 1 / 60;
  68816. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  68817. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  68818. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  68819. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  68820. this._tmpPosition = BABYLON.Vector3.Zero();
  68821. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  68822. this._tmpUnityRotation = new BABYLON.Quaternion();
  68823. if (!this.isSupported()) {
  68824. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  68825. return;
  68826. }
  68827. this._extendNamespace();
  68828. this.world = new this.BJSCANNON.World();
  68829. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  68830. this.world.solver.iterations = iterations;
  68831. }
  68832. CannonJSPlugin.prototype.setGravity = function (gravity) {
  68833. this.world.gravity.copy(gravity);
  68834. };
  68835. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  68836. this._fixedTimeStep = timeStep;
  68837. };
  68838. CannonJSPlugin.prototype.getTimeStep = function () {
  68839. return this._fixedTimeStep;
  68840. };
  68841. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  68842. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  68843. };
  68844. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  68845. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  68846. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  68847. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  68848. };
  68849. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  68850. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  68851. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  68852. impostor.physicsBody.applyForce(impulse, worldPoint);
  68853. };
  68854. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  68855. //parent-child relationship. Does this impostor has a parent impostor?
  68856. if (impostor.parent) {
  68857. if (impostor.physicsBody) {
  68858. this.removePhysicsBody(impostor);
  68859. //TODO is that needed?
  68860. impostor.forceUpdate();
  68861. }
  68862. return;
  68863. }
  68864. //should a new body be created for this impostor?
  68865. if (impostor.isBodyInitRequired()) {
  68866. var shape = this._createShape(impostor);
  68867. //unregister events, if body is being changed
  68868. var oldBody = impostor.physicsBody;
  68869. if (oldBody) {
  68870. this.removePhysicsBody(impostor);
  68871. }
  68872. //create the body and material
  68873. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  68874. var bodyCreationObject = {
  68875. mass: impostor.getParam("mass"),
  68876. material: material
  68877. };
  68878. // A simple extend, in case native options were used.
  68879. var nativeOptions = impostor.getParam("nativeOptions");
  68880. for (var key in nativeOptions) {
  68881. if (nativeOptions.hasOwnProperty(key)) {
  68882. bodyCreationObject[key] = nativeOptions[key];
  68883. }
  68884. }
  68885. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  68886. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  68887. this.world.addEventListener("preStep", impostor.beforeStep);
  68888. this.world.addEventListener("postStep", impostor.afterStep);
  68889. impostor.physicsBody.addShape(shape);
  68890. this.world.add(impostor.physicsBody);
  68891. //try to keep the body moving in the right direction by taking old properties.
  68892. //Should be tested!
  68893. if (oldBody) {
  68894. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  68895. impostor.physicsBody[param].copy(oldBody[param]);
  68896. });
  68897. }
  68898. this._processChildMeshes(impostor);
  68899. }
  68900. //now update the body's transformation
  68901. this._updatePhysicsBodyTransformation(impostor);
  68902. };
  68903. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  68904. var _this = this;
  68905. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  68906. var currentRotation = mainImpostor.object.rotationQuaternion;
  68907. if (meshChildren.length) {
  68908. var processMesh = function (localPosition, mesh) {
  68909. if (!currentRotation || !mesh.rotationQuaternion) {
  68910. return;
  68911. }
  68912. var childImpostor = mesh.getPhysicsImpostor();
  68913. if (childImpostor) {
  68914. var parent = childImpostor.parent;
  68915. if (parent !== mainImpostor) {
  68916. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  68917. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  68918. if (childImpostor.physicsBody) {
  68919. _this.removePhysicsBody(childImpostor);
  68920. childImpostor.physicsBody = null;
  68921. }
  68922. childImpostor.parent = mainImpostor;
  68923. childImpostor.resetUpdateFlags();
  68924. 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));
  68925. //Add the mass of the children.
  68926. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  68927. }
  68928. }
  68929. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  68930. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  68931. };
  68932. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  68933. }
  68934. };
  68935. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  68936. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  68937. this.world.removeEventListener("preStep", impostor.beforeStep);
  68938. this.world.removeEventListener("postStep", impostor.afterStep);
  68939. this.world.remove(impostor.physicsBody);
  68940. };
  68941. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  68942. var mainBody = impostorJoint.mainImpostor.physicsBody;
  68943. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  68944. if (!mainBody || !connectedBody) {
  68945. return;
  68946. }
  68947. var constraint;
  68948. var jointData = impostorJoint.joint.jointData;
  68949. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  68950. var constraintData = {
  68951. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  68952. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  68953. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  68954. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  68955. maxForce: jointData.nativeParams.maxForce,
  68956. collideConnected: !!jointData.collision
  68957. };
  68958. switch (impostorJoint.joint.type) {
  68959. case BABYLON.PhysicsJoint.HingeJoint:
  68960. case BABYLON.PhysicsJoint.Hinge2Joint:
  68961. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  68962. break;
  68963. case BABYLON.PhysicsJoint.DistanceJoint:
  68964. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  68965. break;
  68966. case BABYLON.PhysicsJoint.SpringJoint:
  68967. var springData = jointData;
  68968. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  68969. restLength: springData.length,
  68970. stiffness: springData.stiffness,
  68971. damping: springData.damping,
  68972. localAnchorA: constraintData.pivotA,
  68973. localAnchorB: constraintData.pivotB
  68974. });
  68975. break;
  68976. case BABYLON.PhysicsJoint.LockJoint:
  68977. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  68978. break;
  68979. case BABYLON.PhysicsJoint.PointToPointJoint:
  68980. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  68981. default:
  68982. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  68983. break;
  68984. }
  68985. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  68986. constraint.collideConnected = !!jointData.collision;
  68987. impostorJoint.joint.physicsJoint = constraint;
  68988. //don't add spring as constraint, as it is not one.
  68989. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  68990. this.world.addConstraint(constraint);
  68991. }
  68992. else {
  68993. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  68994. constraint.applyForce();
  68995. });
  68996. }
  68997. };
  68998. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  68999. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  69000. };
  69001. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  69002. var index;
  69003. var mat;
  69004. for (index = 0; index < this._physicsMaterials.length; index++) {
  69005. mat = this._physicsMaterials[index];
  69006. if (mat.friction === friction && mat.restitution === restitution) {
  69007. return mat;
  69008. }
  69009. }
  69010. var currentMat = new this.BJSCANNON.Material(name);
  69011. currentMat.friction = friction;
  69012. currentMat.restitution = restitution;
  69013. this._physicsMaterials.push(currentMat);
  69014. return currentMat;
  69015. };
  69016. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  69017. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  69018. };
  69019. CannonJSPlugin.prototype._createShape = function (impostor) {
  69020. var object = impostor.object;
  69021. var returnValue;
  69022. var extendSize = impostor.getObjectExtendSize();
  69023. switch (impostor.type) {
  69024. case BABYLON.PhysicsImpostor.SphereImpostor:
  69025. var radiusX = extendSize.x;
  69026. var radiusY = extendSize.y;
  69027. var radiusZ = extendSize.z;
  69028. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  69029. break;
  69030. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  69031. case BABYLON.PhysicsImpostor.CylinderImpostor:
  69032. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  69033. break;
  69034. case BABYLON.PhysicsImpostor.BoxImpostor:
  69035. var box = extendSize.scale(0.5);
  69036. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  69037. break;
  69038. case BABYLON.PhysicsImpostor.PlaneImpostor:
  69039. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  69040. returnValue = new this.BJSCANNON.Plane();
  69041. break;
  69042. case BABYLON.PhysicsImpostor.MeshImpostor:
  69043. // should transform the vertex data to world coordinates!!
  69044. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  69045. var rawFaces = object.getIndices ? object.getIndices() : [];
  69046. if (!rawVerts)
  69047. return;
  69048. // get only scale! so the object could transform correctly.
  69049. var oldPosition = object.position.clone();
  69050. var oldRotation = object.rotation && object.rotation.clone();
  69051. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  69052. object.position.copyFromFloats(0, 0, 0);
  69053. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  69054. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  69055. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  69056. var transform = object.computeWorldMatrix(true);
  69057. // convert rawVerts to object space
  69058. var temp = new Array();
  69059. var index;
  69060. for (index = 0; index < rawVerts.length; index += 3) {
  69061. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  69062. }
  69063. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  69064. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  69065. //now set back the transformation!
  69066. object.position.copyFrom(oldPosition);
  69067. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  69068. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  69069. break;
  69070. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  69071. var oldPosition2 = object.position.clone();
  69072. var oldRotation2 = object.rotation && object.rotation.clone();
  69073. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  69074. object.position.copyFromFloats(0, 0, 0);
  69075. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  69076. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  69077. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  69078. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  69079. returnValue = this._createHeightmap(object);
  69080. object.position.copyFrom(oldPosition2);
  69081. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  69082. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  69083. object.computeWorldMatrix(true);
  69084. break;
  69085. case BABYLON.PhysicsImpostor.ParticleImpostor:
  69086. returnValue = new this.BJSCANNON.Particle();
  69087. break;
  69088. }
  69089. return returnValue;
  69090. };
  69091. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  69092. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  69093. var transform = object.computeWorldMatrix(true);
  69094. // convert rawVerts to object space
  69095. var temp = new Array();
  69096. var index;
  69097. for (index = 0; index < pos.length; index += 3) {
  69098. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  69099. }
  69100. pos = temp;
  69101. var matrix = new Array();
  69102. //For now pointDepth will not be used and will be automatically calculated.
  69103. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  69104. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  69105. var boundingInfo = object.getBoundingInfo();
  69106. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  69107. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  69108. var elementSize = dim * 2 / arraySize;
  69109. for (var i = 0; i < pos.length; i = i + 3) {
  69110. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  69111. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  69112. var y = -pos[i + 2] + minY;
  69113. if (!matrix[x]) {
  69114. matrix[x] = [];
  69115. }
  69116. if (!matrix[x][z]) {
  69117. matrix[x][z] = y;
  69118. }
  69119. matrix[x][z] = Math.max(y, matrix[x][z]);
  69120. }
  69121. for (var x = 0; x <= arraySize; ++x) {
  69122. if (!matrix[x]) {
  69123. var loc = 1;
  69124. while (!matrix[(x + loc) % arraySize]) {
  69125. loc++;
  69126. }
  69127. matrix[x] = matrix[(x + loc) % arraySize].slice();
  69128. //console.log("missing x", x);
  69129. }
  69130. for (var z = 0; z <= arraySize; ++z) {
  69131. if (!matrix[x][z]) {
  69132. var loc = 1;
  69133. var newValue;
  69134. while (newValue === undefined) {
  69135. newValue = matrix[x][(z + loc++) % arraySize];
  69136. }
  69137. matrix[x][z] = newValue;
  69138. }
  69139. }
  69140. }
  69141. var shape = new this.BJSCANNON.Heightfield(matrix, {
  69142. elementSize: elementSize
  69143. });
  69144. //For future reference, needed for body transformation
  69145. shape.minY = minY;
  69146. return shape;
  69147. };
  69148. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  69149. var object = impostor.object;
  69150. //make sure it is updated...
  69151. object.computeWorldMatrix && object.computeWorldMatrix(true);
  69152. // The delta between the mesh position and the mesh bounding box center
  69153. var bInfo = object.getBoundingInfo();
  69154. if (!bInfo)
  69155. return;
  69156. var center = impostor.getObjectCenter();
  69157. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  69158. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  69159. this._tmpPosition.copyFrom(center);
  69160. var quaternion = object.rotationQuaternion;
  69161. if (!quaternion) {
  69162. return;
  69163. }
  69164. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  69165. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  69166. //-90 DEG in X, precalculated
  69167. quaternion = quaternion.multiply(this._minus90X);
  69168. //Invert! (Precalculated, 90 deg in X)
  69169. //No need to clone. this will never change.
  69170. impostor.setDeltaRotation(this._plus90X);
  69171. }
  69172. //If it is a heightfield, if should be centered.
  69173. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  69174. var mesh = object;
  69175. var boundingInfo = mesh.getBoundingInfo();
  69176. //calculate the correct body position:
  69177. var rotationQuaternion = mesh.rotationQuaternion;
  69178. mesh.rotationQuaternion = this._tmpUnityRotation;
  69179. mesh.computeWorldMatrix(true);
  69180. //get original center with no rotation
  69181. var c = center.clone();
  69182. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  69183. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  69184. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  69185. mesh.setPivotMatrix(p);
  69186. mesh.computeWorldMatrix(true);
  69187. //calculate the translation
  69188. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  69189. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  69190. //add it inverted to the delta
  69191. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  69192. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  69193. //rotation is back
  69194. mesh.rotationQuaternion = rotationQuaternion;
  69195. mesh.setPivotMatrix(oldPivot);
  69196. mesh.computeWorldMatrix(true);
  69197. }
  69198. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  69199. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  69200. //this._tmpPosition.copyFrom(object.position);
  69201. }
  69202. impostor.setDeltaPosition(this._tmpDeltaPosition);
  69203. //Now update the impostor object
  69204. impostor.physicsBody.position.copy(this._tmpPosition);
  69205. impostor.physicsBody.quaternion.copy(quaternion);
  69206. };
  69207. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  69208. impostor.object.position.copyFrom(impostor.physicsBody.position);
  69209. if (impostor.object.rotationQuaternion) {
  69210. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  69211. }
  69212. };
  69213. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  69214. impostor.physicsBody.position.copy(newPosition);
  69215. impostor.physicsBody.quaternion.copy(newRotation);
  69216. };
  69217. CannonJSPlugin.prototype.isSupported = function () {
  69218. return this.BJSCANNON !== undefined;
  69219. };
  69220. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  69221. impostor.physicsBody.velocity.copy(velocity);
  69222. };
  69223. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  69224. impostor.physicsBody.angularVelocity.copy(velocity);
  69225. };
  69226. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  69227. var v = impostor.physicsBody.velocity;
  69228. if (!v) {
  69229. return null;
  69230. }
  69231. return new BABYLON.Vector3(v.x, v.y, v.z);
  69232. };
  69233. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  69234. var v = impostor.physicsBody.angularVelocity;
  69235. if (!v) {
  69236. return null;
  69237. }
  69238. return new BABYLON.Vector3(v.x, v.y, v.z);
  69239. };
  69240. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  69241. impostor.physicsBody.mass = mass;
  69242. impostor.physicsBody.updateMassProperties();
  69243. };
  69244. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  69245. return impostor.physicsBody.mass;
  69246. };
  69247. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  69248. return impostor.physicsBody.material.friction;
  69249. };
  69250. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  69251. impostor.physicsBody.material.friction = friction;
  69252. };
  69253. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  69254. return impostor.physicsBody.material.restitution;
  69255. };
  69256. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  69257. impostor.physicsBody.material.restitution = restitution;
  69258. };
  69259. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  69260. impostor.physicsBody.sleep();
  69261. };
  69262. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  69263. impostor.physicsBody.wakeUp();
  69264. };
  69265. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  69266. joint.physicsJoint.distance = maxDistance;
  69267. };
  69268. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  69269. // if (!motorIndex) {
  69270. // joint.physicsJoint.enableMotor();
  69271. // }
  69272. // }
  69273. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  69274. // if (!motorIndex) {
  69275. // joint.physicsJoint.disableMotor();
  69276. // }
  69277. // }
  69278. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  69279. if (!motorIndex) {
  69280. joint.physicsJoint.enableMotor();
  69281. joint.physicsJoint.setMotorSpeed(speed);
  69282. if (maxForce) {
  69283. this.setLimit(joint, maxForce);
  69284. }
  69285. }
  69286. };
  69287. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  69288. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  69289. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  69290. };
  69291. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  69292. var body = impostor.physicsBody;
  69293. mesh.position.x = body.position.x;
  69294. mesh.position.y = body.position.y;
  69295. mesh.position.z = body.position.z;
  69296. if (mesh.rotationQuaternion) {
  69297. mesh.rotationQuaternion.x = body.quaternion.x;
  69298. mesh.rotationQuaternion.y = body.quaternion.y;
  69299. mesh.rotationQuaternion.z = body.quaternion.z;
  69300. mesh.rotationQuaternion.w = body.quaternion.w;
  69301. }
  69302. };
  69303. CannonJSPlugin.prototype.getRadius = function (impostor) {
  69304. var shape = impostor.physicsBody.shapes[0];
  69305. return shape.boundingSphereRadius;
  69306. };
  69307. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  69308. var shape = impostor.physicsBody.shapes[0];
  69309. result.x = shape.halfExtents.x * 2;
  69310. result.y = shape.halfExtents.y * 2;
  69311. result.z = shape.halfExtents.z * 2;
  69312. };
  69313. CannonJSPlugin.prototype.dispose = function () {
  69314. };
  69315. CannonJSPlugin.prototype._extendNamespace = function () {
  69316. //this will force cannon to execute at least one step when using interpolation
  69317. var step_tmp1 = new this.BJSCANNON.Vec3();
  69318. var Engine = this.BJSCANNON;
  69319. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  69320. maxSubSteps = maxSubSteps || 10;
  69321. timeSinceLastCalled = timeSinceLastCalled || 0;
  69322. if (timeSinceLastCalled === 0) {
  69323. this.internalStep(dt);
  69324. this.time += dt;
  69325. }
  69326. else {
  69327. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  69328. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  69329. var t0 = performance.now();
  69330. for (var i = 0; i !== internalSteps; i++) {
  69331. this.internalStep(dt);
  69332. if (performance.now() - t0 > dt * 1000) {
  69333. break;
  69334. }
  69335. }
  69336. this.time += timeSinceLastCalled;
  69337. var h = this.time % dt;
  69338. var h_div_dt = h / dt;
  69339. var interpvelo = step_tmp1;
  69340. var bodies = this.bodies;
  69341. for (var j = 0; j !== bodies.length; j++) {
  69342. var b = bodies[j];
  69343. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  69344. b.position.vsub(b.previousPosition, interpvelo);
  69345. interpvelo.scale(h_div_dt, interpvelo);
  69346. b.position.vadd(interpvelo, b.interpolatedPosition);
  69347. }
  69348. else {
  69349. b.interpolatedPosition.copy(b.position);
  69350. b.interpolatedQuaternion.copy(b.quaternion);
  69351. }
  69352. }
  69353. }
  69354. };
  69355. };
  69356. return CannonJSPlugin;
  69357. }());
  69358. BABYLON.CannonJSPlugin = CannonJSPlugin;
  69359. })(BABYLON || (BABYLON = {}));
  69360. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  69361. var BABYLON;
  69362. (function (BABYLON) {
  69363. var OimoJSPlugin = /** @class */ (function () {
  69364. function OimoJSPlugin(iterations) {
  69365. this.name = "OimoJSPlugin";
  69366. this._tmpImpostorsArray = [];
  69367. this._tmpPositionVector = BABYLON.Vector3.Zero();
  69368. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  69369. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  69370. this.world.worldscale(1);
  69371. this.world.clear();
  69372. //making sure no stats are calculated
  69373. this.world.isNoStat = true;
  69374. }
  69375. OimoJSPlugin.prototype.setGravity = function (gravity) {
  69376. this.world.gravity.copy(gravity);
  69377. };
  69378. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  69379. this.world.timeStep = timeStep;
  69380. };
  69381. OimoJSPlugin.prototype.getTimeStep = function () {
  69382. return this.world.timeStep;
  69383. };
  69384. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  69385. var _this = this;
  69386. impostors.forEach(function (impostor) {
  69387. impostor.beforeStep();
  69388. });
  69389. this.world.step();
  69390. impostors.forEach(function (impostor) {
  69391. impostor.afterStep();
  69392. //update the ordered impostors array
  69393. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  69394. });
  69395. //check for collisions
  69396. var contact = this.world.contacts;
  69397. while (contact !== null) {
  69398. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  69399. contact = contact.next;
  69400. continue;
  69401. }
  69402. //is this body colliding with any other? get the impostor
  69403. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  69404. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  69405. if (!mainImpostor || !collidingImpostor) {
  69406. contact = contact.next;
  69407. continue;
  69408. }
  69409. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  69410. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  69411. contact = contact.next;
  69412. }
  69413. };
  69414. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  69415. var mass = impostor.physicsBody.massInfo.mass;
  69416. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  69417. };
  69418. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  69419. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  69420. this.applyImpulse(impostor, force, contactPoint);
  69421. };
  69422. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  69423. var _this = this;
  69424. //parent-child relationship. Does this impostor has a parent impostor?
  69425. if (impostor.parent) {
  69426. if (impostor.physicsBody) {
  69427. this.removePhysicsBody(impostor);
  69428. //TODO is that needed?
  69429. impostor.forceUpdate();
  69430. }
  69431. return;
  69432. }
  69433. if (impostor.isBodyInitRequired()) {
  69434. var bodyConfig = {
  69435. name: impostor.uniqueId,
  69436. //Oimo must have mass, also for static objects.
  69437. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  69438. size: [],
  69439. type: [],
  69440. pos: [],
  69441. rot: [],
  69442. move: impostor.getParam("mass") !== 0,
  69443. //Supporting older versions of Oimo
  69444. world: this.world
  69445. };
  69446. var impostors = [impostor];
  69447. var addToArray = function (parent) {
  69448. if (!parent.getChildMeshes)
  69449. return;
  69450. parent.getChildMeshes().forEach(function (m) {
  69451. if (m.physicsImpostor) {
  69452. impostors.push(m.physicsImpostor);
  69453. //m.physicsImpostor._init();
  69454. }
  69455. });
  69456. };
  69457. addToArray(impostor.object);
  69458. var checkWithEpsilon_1 = function (value) {
  69459. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  69460. };
  69461. impostors.forEach(function (i) {
  69462. if (!impostor.object.rotationQuaternion) {
  69463. return;
  69464. }
  69465. //get the correct bounding box
  69466. var oldQuaternion = i.object.rotationQuaternion;
  69467. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  69468. x: impostor.object.rotationQuaternion.x,
  69469. y: impostor.object.rotationQuaternion.y,
  69470. z: impostor.object.rotationQuaternion.z,
  69471. s: impostor.object.rotationQuaternion.w
  69472. });
  69473. var extendSize = i.getObjectExtendSize();
  69474. if (i === impostor) {
  69475. var center = impostor.getObjectCenter();
  69476. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  69477. //Can also use Array.prototype.push.apply
  69478. bodyConfig.pos.push(center.x);
  69479. bodyConfig.pos.push(center.y);
  69480. bodyConfig.pos.push(center.z);
  69481. //tmp solution
  69482. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  69483. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  69484. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  69485. }
  69486. else {
  69487. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  69488. bodyConfig.pos.push(localPosition.x);
  69489. bodyConfig.pos.push(localPosition.y);
  69490. bodyConfig.pos.push(localPosition.z);
  69491. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  69492. bodyConfig.rot.push(0);
  69493. bodyConfig.rot.push(0);
  69494. bodyConfig.rot.push(0);
  69495. }
  69496. // register mesh
  69497. switch (i.type) {
  69498. case BABYLON.PhysicsImpostor.ParticleImpostor:
  69499. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  69500. case BABYLON.PhysicsImpostor.SphereImpostor:
  69501. var radiusX = extendSize.x;
  69502. var radiusY = extendSize.y;
  69503. var radiusZ = extendSize.z;
  69504. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  69505. bodyConfig.type.push('sphere');
  69506. //due to the way oimo works with compounds, add 3 times
  69507. bodyConfig.size.push(size);
  69508. bodyConfig.size.push(size);
  69509. bodyConfig.size.push(size);
  69510. break;
  69511. case BABYLON.PhysicsImpostor.CylinderImpostor:
  69512. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  69513. var sizeY = checkWithEpsilon_1(extendSize.y);
  69514. bodyConfig.type.push('cylinder');
  69515. bodyConfig.size.push(sizeX);
  69516. bodyConfig.size.push(sizeY);
  69517. //due to the way oimo works with compounds, add one more value.
  69518. bodyConfig.size.push(sizeY);
  69519. break;
  69520. case BABYLON.PhysicsImpostor.PlaneImpostor:
  69521. case BABYLON.PhysicsImpostor.BoxImpostor:
  69522. default:
  69523. var sizeX = checkWithEpsilon_1(extendSize.x);
  69524. var sizeY = checkWithEpsilon_1(extendSize.y);
  69525. var sizeZ = checkWithEpsilon_1(extendSize.z);
  69526. bodyConfig.type.push('box');
  69527. bodyConfig.size.push(sizeX);
  69528. bodyConfig.size.push(sizeY);
  69529. bodyConfig.size.push(sizeZ);
  69530. break;
  69531. }
  69532. //actually not needed, but hey...
  69533. i.object.rotationQuaternion = oldQuaternion;
  69534. });
  69535. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  69536. }
  69537. else {
  69538. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  69539. }
  69540. impostor.setDeltaPosition(this._tmpPositionVector);
  69541. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  69542. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  69543. };
  69544. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  69545. //impostor.physicsBody.dispose();
  69546. //Same as : (older oimo versions)
  69547. this.world.removeRigidBody(impostor.physicsBody);
  69548. };
  69549. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  69550. var mainBody = impostorJoint.mainImpostor.physicsBody;
  69551. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  69552. if (!mainBody || !connectedBody) {
  69553. return;
  69554. }
  69555. var jointData = impostorJoint.joint.jointData;
  69556. var options = jointData.nativeParams || {};
  69557. var type;
  69558. var nativeJointData = {
  69559. body1: mainBody,
  69560. body2: connectedBody,
  69561. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  69562. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  69563. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  69564. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  69565. min: options.min,
  69566. max: options.max,
  69567. collision: options.collision || jointData.collision,
  69568. spring: options.spring,
  69569. //supporting older version of Oimo
  69570. world: this.world
  69571. };
  69572. switch (impostorJoint.joint.type) {
  69573. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  69574. type = "jointBall";
  69575. break;
  69576. case BABYLON.PhysicsJoint.SpringJoint:
  69577. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  69578. var springData = jointData;
  69579. nativeJointData.min = springData.length || nativeJointData.min;
  69580. //Max should also be set, just make sure it is at least min
  69581. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  69582. case BABYLON.PhysicsJoint.DistanceJoint:
  69583. type = "jointDistance";
  69584. nativeJointData.max = jointData.maxDistance;
  69585. break;
  69586. case BABYLON.PhysicsJoint.PrismaticJoint:
  69587. type = "jointPrisme";
  69588. break;
  69589. case BABYLON.PhysicsJoint.SliderJoint:
  69590. type = "jointSlide";
  69591. break;
  69592. case BABYLON.PhysicsJoint.WheelJoint:
  69593. type = "jointWheel";
  69594. break;
  69595. case BABYLON.PhysicsJoint.HingeJoint:
  69596. default:
  69597. type = "jointHinge";
  69598. break;
  69599. }
  69600. nativeJointData.type = type;
  69601. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  69602. };
  69603. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  69604. //Bug in Oimo prevents us from disposing a joint in the playground
  69605. //joint.joint.physicsJoint.dispose();
  69606. //So we will bruteforce it!
  69607. try {
  69608. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  69609. }
  69610. catch (e) {
  69611. BABYLON.Tools.Warn(e);
  69612. }
  69613. };
  69614. OimoJSPlugin.prototype.isSupported = function () {
  69615. return this.BJSOIMO !== undefined;
  69616. };
  69617. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  69618. if (!impostor.physicsBody.sleeping) {
  69619. //TODO check that
  69620. if (impostor.physicsBody.shapes.next) {
  69621. var parentShape = this._getLastShape(impostor.physicsBody);
  69622. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  69623. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  69624. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  69625. }
  69626. else {
  69627. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  69628. }
  69629. if (impostor.object.rotationQuaternion) {
  69630. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  69631. impostor.object.rotationQuaternion.normalize();
  69632. }
  69633. }
  69634. };
  69635. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  69636. var body = impostor.physicsBody;
  69637. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  69638. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  69639. body.syncShapes();
  69640. body.awake();
  69641. };
  69642. OimoJSPlugin.prototype._getLastShape = function (body) {
  69643. var lastShape = body.shapes;
  69644. while (lastShape.next) {
  69645. lastShape = lastShape.next;
  69646. }
  69647. return lastShape;
  69648. };
  69649. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  69650. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  69651. };
  69652. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  69653. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  69654. };
  69655. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  69656. var v = impostor.physicsBody.linearVelocity;
  69657. if (!v) {
  69658. return null;
  69659. }
  69660. return new BABYLON.Vector3(v.x, v.y, v.z);
  69661. };
  69662. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  69663. var v = impostor.physicsBody.angularVelocity;
  69664. if (!v) {
  69665. return null;
  69666. }
  69667. return new BABYLON.Vector3(v.x, v.y, v.z);
  69668. };
  69669. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  69670. var staticBody = mass === 0;
  69671. //this will actually set the body's density and not its mass.
  69672. //But this is how oimo treats the mass variable.
  69673. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  69674. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  69675. };
  69676. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  69677. return impostor.physicsBody.shapes.density;
  69678. };
  69679. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  69680. return impostor.physicsBody.shapes.friction;
  69681. };
  69682. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  69683. impostor.physicsBody.shapes.friction = friction;
  69684. };
  69685. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  69686. return impostor.physicsBody.shapes.restitution;
  69687. };
  69688. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  69689. impostor.physicsBody.shapes.restitution = restitution;
  69690. };
  69691. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  69692. impostor.physicsBody.sleep();
  69693. };
  69694. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  69695. impostor.physicsBody.awake();
  69696. };
  69697. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  69698. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  69699. if (minDistance !== void 0) {
  69700. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  69701. }
  69702. };
  69703. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  69704. //TODO separate rotational and transational motors.
  69705. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  69706. if (motor) {
  69707. motor.setMotor(speed, maxForce);
  69708. }
  69709. };
  69710. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  69711. //TODO separate rotational and transational motors.
  69712. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  69713. if (motor) {
  69714. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  69715. }
  69716. };
  69717. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  69718. var body = impostor.physicsBody;
  69719. mesh.position.x = body.position.x;
  69720. mesh.position.y = body.position.y;
  69721. mesh.position.z = body.position.z;
  69722. if (mesh.rotationQuaternion) {
  69723. mesh.rotationQuaternion.x = body.orientation.x;
  69724. mesh.rotationQuaternion.y = body.orientation.y;
  69725. mesh.rotationQuaternion.z = body.orientation.z;
  69726. mesh.rotationQuaternion.w = body.orientation.s;
  69727. }
  69728. };
  69729. OimoJSPlugin.prototype.getRadius = function (impostor) {
  69730. return impostor.physicsBody.shapes.radius;
  69731. };
  69732. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  69733. var shape = impostor.physicsBody.shapes;
  69734. result.x = shape.halfWidth * 2;
  69735. result.y = shape.halfHeight * 2;
  69736. result.z = shape.halfDepth * 2;
  69737. };
  69738. OimoJSPlugin.prototype.dispose = function () {
  69739. this.world.clear();
  69740. };
  69741. return OimoJSPlugin;
  69742. }());
  69743. BABYLON.OimoJSPlugin = OimoJSPlugin;
  69744. })(BABYLON || (BABYLON = {}));
  69745. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  69746. var BABYLON;
  69747. (function (BABYLON) {
  69748. var Internals;
  69749. (function (Internals) {
  69750. /*
  69751. * Based on jsTGALoader - Javascript loader for TGA file
  69752. * By Vincent Thibault
  69753. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  69754. */
  69755. var TGATools = /** @class */ (function () {
  69756. function TGATools() {
  69757. }
  69758. TGATools.GetTGAHeader = function (data) {
  69759. var offset = 0;
  69760. var header = {
  69761. id_length: data[offset++],
  69762. colormap_type: data[offset++],
  69763. image_type: data[offset++],
  69764. colormap_index: data[offset++] | data[offset++] << 8,
  69765. colormap_length: data[offset++] | data[offset++] << 8,
  69766. colormap_size: data[offset++],
  69767. origin: [
  69768. data[offset++] | data[offset++] << 8,
  69769. data[offset++] | data[offset++] << 8
  69770. ],
  69771. width: data[offset++] | data[offset++] << 8,
  69772. height: data[offset++] | data[offset++] << 8,
  69773. pixel_size: data[offset++],
  69774. flags: data[offset++]
  69775. };
  69776. return header;
  69777. };
  69778. TGATools.UploadContent = function (gl, data) {
  69779. // Not enough data to contain header ?
  69780. if (data.length < 19) {
  69781. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  69782. return;
  69783. }
  69784. // Read Header
  69785. var offset = 18;
  69786. var header = TGATools.GetTGAHeader(data);
  69787. // Assume it's a valid Targa file.
  69788. if (header.id_length + offset > data.length) {
  69789. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  69790. return;
  69791. }
  69792. // Skip not needed data
  69793. offset += header.id_length;
  69794. var use_rle = false;
  69795. var use_pal = false;
  69796. var use_grey = false;
  69797. // Get some informations.
  69798. switch (header.image_type) {
  69799. case TGATools._TYPE_RLE_INDEXED:
  69800. use_rle = true;
  69801. case TGATools._TYPE_INDEXED:
  69802. use_pal = true;
  69803. break;
  69804. case TGATools._TYPE_RLE_RGB:
  69805. use_rle = true;
  69806. case TGATools._TYPE_RGB:
  69807. // use_rgb = true;
  69808. break;
  69809. case TGATools._TYPE_RLE_GREY:
  69810. use_rle = true;
  69811. case TGATools._TYPE_GREY:
  69812. use_grey = true;
  69813. break;
  69814. }
  69815. var pixel_data;
  69816. // var numAlphaBits = header.flags & 0xf;
  69817. var pixel_size = header.pixel_size >> 3;
  69818. var pixel_total = header.width * header.height * pixel_size;
  69819. // Read palettes
  69820. var palettes;
  69821. if (use_pal) {
  69822. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  69823. }
  69824. // Read LRE
  69825. if (use_rle) {
  69826. pixel_data = new Uint8Array(pixel_total);
  69827. var c, count, i;
  69828. var localOffset = 0;
  69829. var pixels = new Uint8Array(pixel_size);
  69830. while (offset < pixel_total && localOffset < pixel_total) {
  69831. c = data[offset++];
  69832. count = (c & 0x7f) + 1;
  69833. // RLE pixels
  69834. if (c & 0x80) {
  69835. // Bind pixel tmp array
  69836. for (i = 0; i < pixel_size; ++i) {
  69837. pixels[i] = data[offset++];
  69838. }
  69839. // Copy pixel array
  69840. for (i = 0; i < count; ++i) {
  69841. pixel_data.set(pixels, localOffset + i * pixel_size);
  69842. }
  69843. localOffset += pixel_size * count;
  69844. }
  69845. else {
  69846. count *= pixel_size;
  69847. for (i = 0; i < count; ++i) {
  69848. pixel_data[localOffset + i] = data[offset++];
  69849. }
  69850. localOffset += count;
  69851. }
  69852. }
  69853. }
  69854. else {
  69855. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  69856. }
  69857. // Load to texture
  69858. var x_start, y_start, x_step, y_step, y_end, x_end;
  69859. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  69860. default:
  69861. case TGATools._ORIGIN_UL:
  69862. x_start = 0;
  69863. x_step = 1;
  69864. x_end = header.width;
  69865. y_start = 0;
  69866. y_step = 1;
  69867. y_end = header.height;
  69868. break;
  69869. case TGATools._ORIGIN_BL:
  69870. x_start = 0;
  69871. x_step = 1;
  69872. x_end = header.width;
  69873. y_start = header.height - 1;
  69874. y_step = -1;
  69875. y_end = -1;
  69876. break;
  69877. case TGATools._ORIGIN_UR:
  69878. x_start = header.width - 1;
  69879. x_step = -1;
  69880. x_end = -1;
  69881. y_start = 0;
  69882. y_step = 1;
  69883. y_end = header.height;
  69884. break;
  69885. case TGATools._ORIGIN_BR:
  69886. x_start = header.width - 1;
  69887. x_step = -1;
  69888. x_end = -1;
  69889. y_start = header.height - 1;
  69890. y_step = -1;
  69891. y_end = -1;
  69892. break;
  69893. }
  69894. // Load the specify method
  69895. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  69896. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  69897. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  69898. };
  69899. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  69900. var image = pixel_data, colormap = palettes;
  69901. var width = header.width, height = header.height;
  69902. var color, i = 0, x, y;
  69903. var imageData = new Uint8Array(width * height * 4);
  69904. for (y = y_start; y !== y_end; y += y_step) {
  69905. for (x = x_start; x !== x_end; x += x_step, i++) {
  69906. color = image[i];
  69907. imageData[(x + width * y) * 4 + 3] = 255;
  69908. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  69909. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  69910. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  69911. }
  69912. }
  69913. return imageData;
  69914. };
  69915. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  69916. var image = pixel_data;
  69917. var width = header.width, height = header.height;
  69918. var color, i = 0, x, y;
  69919. var imageData = new Uint8Array(width * height * 4);
  69920. for (y = y_start; y !== y_end; y += y_step) {
  69921. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  69922. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  69923. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  69924. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  69925. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  69926. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  69927. }
  69928. }
  69929. return imageData;
  69930. };
  69931. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  69932. var image = pixel_data;
  69933. var width = header.width, height = header.height;
  69934. var i = 0, x, y;
  69935. var imageData = new Uint8Array(width * height * 4);
  69936. for (y = y_start; y !== y_end; y += y_step) {
  69937. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  69938. imageData[(x + width * y) * 4 + 3] = 255;
  69939. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  69940. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  69941. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  69942. }
  69943. }
  69944. return imageData;
  69945. };
  69946. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  69947. var image = pixel_data;
  69948. var width = header.width, height = header.height;
  69949. var i = 0, x, y;
  69950. var imageData = new Uint8Array(width * height * 4);
  69951. for (y = y_start; y !== y_end; y += y_step) {
  69952. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  69953. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  69954. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  69955. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  69956. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  69957. }
  69958. }
  69959. return imageData;
  69960. };
  69961. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  69962. var image = pixel_data;
  69963. var width = header.width, height = header.height;
  69964. var color, i = 0, x, y;
  69965. var imageData = new Uint8Array(width * height * 4);
  69966. for (y = y_start; y !== y_end; y += y_step) {
  69967. for (x = x_start; x !== x_end; x += x_step, i++) {
  69968. color = image[i];
  69969. imageData[(x + width * y) * 4 + 0] = color;
  69970. imageData[(x + width * y) * 4 + 1] = color;
  69971. imageData[(x + width * y) * 4 + 2] = color;
  69972. imageData[(x + width * y) * 4 + 3] = 255;
  69973. }
  69974. }
  69975. return imageData;
  69976. };
  69977. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  69978. var image = pixel_data;
  69979. var width = header.width, height = header.height;
  69980. var i = 0, x, y;
  69981. var imageData = new Uint8Array(width * height * 4);
  69982. for (y = y_start; y !== y_end; y += y_step) {
  69983. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  69984. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  69985. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  69986. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  69987. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  69988. }
  69989. }
  69990. return imageData;
  69991. };
  69992. //private static _TYPE_NO_DATA = 0;
  69993. TGATools._TYPE_INDEXED = 1;
  69994. TGATools._TYPE_RGB = 2;
  69995. TGATools._TYPE_GREY = 3;
  69996. TGATools._TYPE_RLE_INDEXED = 9;
  69997. TGATools._TYPE_RLE_RGB = 10;
  69998. TGATools._TYPE_RLE_GREY = 11;
  69999. TGATools._ORIGIN_MASK = 0x30;
  70000. TGATools._ORIGIN_SHIFT = 0x04;
  70001. TGATools._ORIGIN_BL = 0x00;
  70002. TGATools._ORIGIN_BR = 0x01;
  70003. TGATools._ORIGIN_UL = 0x02;
  70004. TGATools._ORIGIN_UR = 0x03;
  70005. return TGATools;
  70006. }());
  70007. Internals.TGATools = TGATools;
  70008. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  70009. })(BABYLON || (BABYLON = {}));
  70010. //# sourceMappingURL=babylon.tga.js.map
  70011. var BABYLON;
  70012. (function (BABYLON) {
  70013. var Internals;
  70014. (function (Internals) {
  70015. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  70016. // All values and structures referenced from:
  70017. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  70018. var DDS_MAGIC = 0x20534444;
  70019. var
  70020. //DDSD_CAPS = 0x1,
  70021. //DDSD_HEIGHT = 0x2,
  70022. //DDSD_WIDTH = 0x4,
  70023. //DDSD_PITCH = 0x8,
  70024. //DDSD_PIXELFORMAT = 0x1000,
  70025. DDSD_MIPMAPCOUNT = 0x20000;
  70026. //DDSD_LINEARSIZE = 0x80000,
  70027. //DDSD_DEPTH = 0x800000;
  70028. // var DDSCAPS_COMPLEX = 0x8,
  70029. // DDSCAPS_MIPMAP = 0x400000,
  70030. // DDSCAPS_TEXTURE = 0x1000;
  70031. var DDSCAPS2_CUBEMAP = 0x200;
  70032. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  70033. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  70034. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  70035. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  70036. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  70037. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  70038. // DDSCAPS2_VOLUME = 0x200000;
  70039. var
  70040. //DDPF_ALPHAPIXELS = 0x1,
  70041. //DDPF_ALPHA = 0x2,
  70042. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  70043. //DDPF_YUV = 0x200,
  70044. DDPF_LUMINANCE = 0x20000;
  70045. function FourCCToInt32(value) {
  70046. return value.charCodeAt(0) +
  70047. (value.charCodeAt(1) << 8) +
  70048. (value.charCodeAt(2) << 16) +
  70049. (value.charCodeAt(3) << 24);
  70050. }
  70051. function Int32ToFourCC(value) {
  70052. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  70053. }
  70054. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  70055. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  70056. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  70057. var FOURCC_DX10 = FourCCToInt32("DX10");
  70058. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  70059. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  70060. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  70061. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  70062. var headerLengthInt = 31; // The header length in 32 bit ints
  70063. // Offsets into the header array
  70064. var off_magic = 0;
  70065. var off_size = 1;
  70066. var off_flags = 2;
  70067. var off_height = 3;
  70068. var off_width = 4;
  70069. var off_mipmapCount = 7;
  70070. var off_pfFlags = 20;
  70071. var off_pfFourCC = 21;
  70072. var off_RGBbpp = 22;
  70073. // var off_RMask = 23;
  70074. // var off_GMask = 24;
  70075. // var off_BMask = 25;
  70076. // var off_AMask = 26;
  70077. // var off_caps1 = 27;
  70078. var off_caps2 = 28;
  70079. // var off_caps3 = 29;
  70080. // var off_caps4 = 30;
  70081. var off_dxgiFormat = 32;
  70082. ;
  70083. var DDSTools = /** @class */ (function () {
  70084. function DDSTools() {
  70085. }
  70086. DDSTools.GetDDSInfo = function (arrayBuffer) {
  70087. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  70088. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  70089. var mipmapCount = 1;
  70090. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  70091. mipmapCount = Math.max(1, header[off_mipmapCount]);
  70092. }
  70093. var fourCC = header[off_pfFourCC];
  70094. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  70095. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70096. switch (fourCC) {
  70097. case FOURCC_D3DFMT_R16G16B16A16F:
  70098. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70099. break;
  70100. case FOURCC_D3DFMT_R32G32B32A32F:
  70101. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70102. break;
  70103. case FOURCC_DX10:
  70104. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  70105. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70106. break;
  70107. }
  70108. }
  70109. return {
  70110. width: header[off_width],
  70111. height: header[off_height],
  70112. mipmapCount: mipmapCount,
  70113. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  70114. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  70115. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  70116. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  70117. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  70118. dxgiFormat: dxgiFormat,
  70119. textureType: textureType
  70120. };
  70121. };
  70122. DDSTools._ToHalfFloat = function (value) {
  70123. if (!DDSTools._FloatView) {
  70124. DDSTools._FloatView = new Float32Array(1);
  70125. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  70126. }
  70127. DDSTools._FloatView[0] = value;
  70128. var x = DDSTools._Int32View[0];
  70129. var bits = (x >> 16) & 0x8000; /* Get the sign */
  70130. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  70131. var e = (x >> 23) & 0xff; /* Using int is faster here */
  70132. /* If zero, or denormal, or exponent underflows too much for a denormal
  70133. * half, return signed zero. */
  70134. if (e < 103) {
  70135. return bits;
  70136. }
  70137. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  70138. if (e > 142) {
  70139. bits |= 0x7c00;
  70140. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  70141. * not Inf, so make sure we set one mantissa bit too. */
  70142. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  70143. return bits;
  70144. }
  70145. /* If exponent underflows but not too much, return a denormal */
  70146. if (e < 113) {
  70147. m |= 0x0800;
  70148. /* Extra rounding may overflow and set mantissa to 0 and exponent
  70149. * to 1, which is OK. */
  70150. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  70151. return bits;
  70152. }
  70153. bits |= ((e - 112) << 10) | (m >> 1);
  70154. bits += m & 1;
  70155. return bits;
  70156. };
  70157. DDSTools._FromHalfFloat = function (value) {
  70158. var s = (value & 0x8000) >> 15;
  70159. var e = (value & 0x7C00) >> 10;
  70160. var f = value & 0x03FF;
  70161. if (e === 0) {
  70162. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  70163. }
  70164. else if (e == 0x1F) {
  70165. return f ? NaN : ((s ? -1 : 1) * Infinity);
  70166. }
  70167. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  70168. };
  70169. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  70170. var destArray = new Float32Array(dataLength);
  70171. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  70172. var index = 0;
  70173. for (var y = 0; y < height; y++) {
  70174. for (var x = 0; x < width; x++) {
  70175. var srcPos = (x + y * width) * 4;
  70176. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  70177. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  70178. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  70179. if (DDSTools.StoreLODInAlphaChannel) {
  70180. destArray[index + 3] = lod;
  70181. }
  70182. else {
  70183. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  70184. }
  70185. index += 4;
  70186. }
  70187. }
  70188. return destArray;
  70189. };
  70190. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  70191. if (DDSTools.StoreLODInAlphaChannel) {
  70192. var destArray = new Uint16Array(dataLength);
  70193. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  70194. var index = 0;
  70195. for (var y = 0; y < height; y++) {
  70196. for (var x = 0; x < width; x++) {
  70197. var srcPos = (x + y * width) * 4;
  70198. destArray[index] = srcData[srcPos];
  70199. destArray[index + 1] = srcData[srcPos + 1];
  70200. destArray[index + 2] = srcData[srcPos + 2];
  70201. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  70202. index += 4;
  70203. }
  70204. }
  70205. return destArray;
  70206. }
  70207. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  70208. };
  70209. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  70210. if (DDSTools.StoreLODInAlphaChannel) {
  70211. var destArray = new Float32Array(dataLength);
  70212. var srcData = new Float32Array(arrayBuffer, dataOffset);
  70213. var index = 0;
  70214. for (var y = 0; y < height; y++) {
  70215. for (var x = 0; x < width; x++) {
  70216. var srcPos = (x + y * width) * 4;
  70217. destArray[index] = srcData[srcPos];
  70218. destArray[index + 1] = srcData[srcPos + 1];
  70219. destArray[index + 2] = srcData[srcPos + 2];
  70220. destArray[index + 3] = lod;
  70221. index += 4;
  70222. }
  70223. }
  70224. return destArray;
  70225. }
  70226. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  70227. };
  70228. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  70229. var destArray = new Uint8Array(dataLength);
  70230. var srcData = new Float32Array(arrayBuffer, dataOffset);
  70231. var index = 0;
  70232. for (var y = 0; y < height; y++) {
  70233. for (var x = 0; x < width; x++) {
  70234. var srcPos = (x + y * width) * 4;
  70235. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  70236. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  70237. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  70238. if (DDSTools.StoreLODInAlphaChannel) {
  70239. destArray[index + 3] = lod;
  70240. }
  70241. else {
  70242. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  70243. }
  70244. index += 4;
  70245. }
  70246. }
  70247. return destArray;
  70248. };
  70249. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  70250. var destArray = new Uint8Array(dataLength);
  70251. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  70252. var index = 0;
  70253. for (var y = 0; y < height; y++) {
  70254. for (var x = 0; x < width; x++) {
  70255. var srcPos = (x + y * width) * 4;
  70256. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  70257. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  70258. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  70259. if (DDSTools.StoreLODInAlphaChannel) {
  70260. destArray[index + 3] = lod;
  70261. }
  70262. else {
  70263. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  70264. }
  70265. index += 4;
  70266. }
  70267. }
  70268. return destArray;
  70269. };
  70270. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  70271. var byteArray = new Uint8Array(dataLength);
  70272. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  70273. var index = 0;
  70274. for (var y = 0; y < height; y++) {
  70275. for (var x = 0; x < width; x++) {
  70276. var srcPos = (x + y * width) * 4;
  70277. byteArray[index] = srcData[srcPos + 2];
  70278. byteArray[index + 1] = srcData[srcPos + 1];
  70279. byteArray[index + 2] = srcData[srcPos];
  70280. byteArray[index + 3] = srcData[srcPos + 3];
  70281. index += 4;
  70282. }
  70283. }
  70284. return byteArray;
  70285. };
  70286. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  70287. var byteArray = new Uint8Array(dataLength);
  70288. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  70289. var index = 0;
  70290. for (var y = 0; y < height; y++) {
  70291. for (var x = 0; x < width; x++) {
  70292. var srcPos = (x + y * width) * 3;
  70293. byteArray[index] = srcData[srcPos + 2];
  70294. byteArray[index + 1] = srcData[srcPos + 1];
  70295. byteArray[index + 2] = srcData[srcPos];
  70296. index += 3;
  70297. }
  70298. }
  70299. return byteArray;
  70300. };
  70301. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  70302. var byteArray = new Uint8Array(dataLength);
  70303. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  70304. var index = 0;
  70305. for (var y = 0; y < height; y++) {
  70306. for (var x = 0; x < width; x++) {
  70307. var srcPos = (x + y * width);
  70308. byteArray[index] = srcData[srcPos];
  70309. index++;
  70310. }
  70311. }
  70312. return byteArray;
  70313. };
  70314. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  70315. if (lodIndex === void 0) { lodIndex = -1; }
  70316. var ext = engine.getCaps().s3tc;
  70317. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  70318. var fourCC, width, height, dataLength = 0, dataOffset;
  70319. var byteArray, mipmapCount, mip;
  70320. var internalFormat = 0;
  70321. var format = 0;
  70322. var blockBytes = 1;
  70323. if (header[off_magic] !== DDS_MAGIC) {
  70324. BABYLON.Tools.Error("Invalid magic number in DDS header");
  70325. return;
  70326. }
  70327. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  70328. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  70329. return;
  70330. }
  70331. if (info.isCompressed && !ext) {
  70332. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  70333. return;
  70334. }
  70335. var bpp = header[off_RGBbpp];
  70336. dataOffset = header[off_size] + 4;
  70337. var computeFormats = false;
  70338. if (info.isFourCC) {
  70339. fourCC = header[off_pfFourCC];
  70340. switch (fourCC) {
  70341. case FOURCC_DXT1:
  70342. blockBytes = 8;
  70343. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  70344. break;
  70345. case FOURCC_DXT3:
  70346. blockBytes = 16;
  70347. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  70348. break;
  70349. case FOURCC_DXT5:
  70350. blockBytes = 16;
  70351. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  70352. break;
  70353. case FOURCC_D3DFMT_R16G16B16A16F:
  70354. computeFormats = true;
  70355. break;
  70356. case FOURCC_D3DFMT_R32G32B32A32F:
  70357. computeFormats = true;
  70358. break;
  70359. case FOURCC_DX10:
  70360. // There is an additionnal header so dataOffset need to be changed
  70361. dataOffset += 5 * 4; // 5 uints
  70362. var supported = false;
  70363. switch (info.dxgiFormat) {
  70364. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  70365. computeFormats = true;
  70366. supported = true;
  70367. break;
  70368. case DXGI_FORMAT_B8G8R8X8_UNORM:
  70369. info.isRGB = true;
  70370. info.isFourCC = false;
  70371. bpp = 32;
  70372. supported = true;
  70373. break;
  70374. }
  70375. if (supported) {
  70376. break;
  70377. }
  70378. default:
  70379. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  70380. return;
  70381. }
  70382. }
  70383. if (computeFormats) {
  70384. format = engine._getWebGLTextureType(info.textureType);
  70385. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  70386. }
  70387. mipmapCount = 1;
  70388. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  70389. mipmapCount = Math.max(1, header[off_mipmapCount]);
  70390. }
  70391. for (var face = 0; face < faces; face++) {
  70392. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  70393. width = header[off_width];
  70394. height = header[off_height];
  70395. for (mip = 0; mip < mipmapCount; ++mip) {
  70396. if (lodIndex === -1 || lodIndex === mip) {
  70397. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  70398. var i = (lodIndex === -1) ? mip : 0;
  70399. if (!info.isCompressed && info.isFourCC) {
  70400. dataLength = width * height * 4;
  70401. var floatArray = null;
  70402. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  70403. if (bpp === 128) {
  70404. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  70405. }
  70406. else if (bpp === 64) {
  70407. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  70408. }
  70409. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70410. format = engine._getWebGLTextureType(info.textureType);
  70411. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  70412. }
  70413. else {
  70414. if (bpp === 128) {
  70415. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  70416. }
  70417. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  70418. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  70419. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70420. format = engine._getWebGLTextureType(info.textureType);
  70421. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  70422. }
  70423. else {
  70424. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  70425. }
  70426. }
  70427. if (floatArray) {
  70428. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  70429. }
  70430. }
  70431. else if (info.isRGB) {
  70432. if (bpp === 24) {
  70433. dataLength = width * height * 3;
  70434. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  70435. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  70436. }
  70437. else {
  70438. dataLength = width * height * 4;
  70439. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  70440. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  70441. }
  70442. }
  70443. else if (info.isLuminance) {
  70444. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  70445. var unpaddedRowSize = width;
  70446. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  70447. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  70448. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  70449. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  70450. }
  70451. else {
  70452. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  70453. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  70454. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  70455. }
  70456. }
  70457. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  70458. width *= 0.5;
  70459. height *= 0.5;
  70460. width = Math.max(1.0, width);
  70461. height = Math.max(1.0, height);
  70462. }
  70463. if (currentFace !== undefined) {
  70464. // Loading a single face
  70465. break;
  70466. }
  70467. }
  70468. };
  70469. DDSTools.StoreLODInAlphaChannel = false;
  70470. return DDSTools;
  70471. }());
  70472. Internals.DDSTools = DDSTools;
  70473. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  70474. })(BABYLON || (BABYLON = {}));
  70475. //# sourceMappingURL=babylon.dds.js.map
  70476. var BABYLON;
  70477. (function (BABYLON) {
  70478. var Internals;
  70479. (function (Internals) {
  70480. /**
  70481. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  70482. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  70483. */
  70484. var KhronosTextureContainer = /** @class */ (function () {
  70485. /**
  70486. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  70487. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  70488. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  70489. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  70490. */
  70491. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  70492. this.arrayBuffer = arrayBuffer;
  70493. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  70494. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  70495. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  70496. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  70497. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  70498. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  70499. BABYLON.Tools.Error("texture missing KTX identifier");
  70500. return;
  70501. }
  70502. // load the reset of the header in native 32 bit int
  70503. var header = new Int32Array(this.arrayBuffer, 12, 13);
  70504. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  70505. var oppositeEndianess = header[0] === 0x01020304;
  70506. // read all the header elements in order they exist in the file, without modification (sans endainness)
  70507. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  70508. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  70509. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  70510. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  70511. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  70512. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  70513. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  70514. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  70515. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  70516. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  70517. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  70518. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  70519. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  70520. if (this.glType !== 0) {
  70521. BABYLON.Tools.Error("only compressed formats currently supported");
  70522. return;
  70523. }
  70524. else {
  70525. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  70526. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  70527. }
  70528. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  70529. BABYLON.Tools.Error("only 2D textures currently supported");
  70530. return;
  70531. }
  70532. if (this.numberOfArrayElements !== 0) {
  70533. BABYLON.Tools.Error("texture arrays not currently supported");
  70534. return;
  70535. }
  70536. if (this.numberOfFaces !== facesExpected) {
  70537. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  70538. return;
  70539. }
  70540. // we now have a completely validated file, so could use existence of loadType as success
  70541. // would need to make this more elaborate & adjust checks above to support more than one load type
  70542. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  70543. }
  70544. // not as fast hardware based, but will probably never need to use
  70545. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  70546. return ((val & 0xFF) << 24)
  70547. | ((val & 0xFF00) << 8)
  70548. | ((val >> 8) & 0xFF00)
  70549. | ((val >> 24) & 0xFF);
  70550. };
  70551. /**
  70552. * It is assumed that the texture has already been created & is currently bound
  70553. */
  70554. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  70555. switch (this.loadType) {
  70556. case KhronosTextureContainer.COMPRESSED_2D:
  70557. this._upload2DCompressedLevels(gl, loadMipmaps);
  70558. break;
  70559. case KhronosTextureContainer.TEX_2D:
  70560. case KhronosTextureContainer.COMPRESSED_3D:
  70561. case KhronosTextureContainer.TEX_3D:
  70562. }
  70563. };
  70564. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  70565. // initialize width & height for level 1
  70566. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  70567. var width = this.pixelWidth;
  70568. var height = this.pixelHeight;
  70569. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  70570. for (var level = 0; level < mipmapCount; level++) {
  70571. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  70572. for (var face = 0; face < this.numberOfFaces; face++) {
  70573. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  70574. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  70575. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  70576. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  70577. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  70578. }
  70579. width = Math.max(1.0, width * 0.5);
  70580. height = Math.max(1.0, height * 0.5);
  70581. }
  70582. };
  70583. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  70584. // load types
  70585. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  70586. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  70587. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  70588. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  70589. return KhronosTextureContainer;
  70590. }());
  70591. Internals.KhronosTextureContainer = KhronosTextureContainer;
  70592. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  70593. })(BABYLON || (BABYLON = {}));
  70594. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  70595. var BABYLON;
  70596. (function (BABYLON) {
  70597. var Debug;
  70598. (function (Debug) {
  70599. /**
  70600. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  70601. */
  70602. var SkeletonViewer = /** @class */ (function () {
  70603. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  70604. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  70605. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  70606. this.skeleton = skeleton;
  70607. this.mesh = mesh;
  70608. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  70609. this.renderingGroupId = renderingGroupId;
  70610. this.color = BABYLON.Color3.White();
  70611. this._debugLines = new Array();
  70612. this._isEnabled = false;
  70613. this._scene = scene;
  70614. this.update();
  70615. this._renderFunction = this.update.bind(this);
  70616. }
  70617. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  70618. get: function () {
  70619. return this._isEnabled;
  70620. },
  70621. set: function (value) {
  70622. if (this._isEnabled === value) {
  70623. return;
  70624. }
  70625. this._isEnabled = value;
  70626. if (value) {
  70627. this._scene.registerBeforeRender(this._renderFunction);
  70628. }
  70629. else {
  70630. this._scene.unregisterBeforeRender(this._renderFunction);
  70631. }
  70632. },
  70633. enumerable: true,
  70634. configurable: true
  70635. });
  70636. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  70637. if (x === void 0) { x = 0; }
  70638. if (y === void 0) { y = 0; }
  70639. if (z === void 0) { z = 0; }
  70640. var tmat = BABYLON.Tmp.Matrix[0];
  70641. var parentBone = bone.getParent();
  70642. tmat.copyFrom(bone.getLocalMatrix());
  70643. if (x !== 0 || y !== 0 || z !== 0) {
  70644. var tmat2 = BABYLON.Tmp.Matrix[1];
  70645. BABYLON.Matrix.IdentityToRef(tmat2);
  70646. tmat2.m[12] = x;
  70647. tmat2.m[13] = y;
  70648. tmat2.m[14] = z;
  70649. tmat2.multiplyToRef(tmat, tmat);
  70650. }
  70651. if (parentBone) {
  70652. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  70653. }
  70654. tmat.multiplyToRef(meshMat, tmat);
  70655. position.x = tmat.m[12];
  70656. position.y = tmat.m[13];
  70657. position.z = tmat.m[14];
  70658. };
  70659. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  70660. var len = bones.length;
  70661. var meshPos = this.mesh.position;
  70662. for (var i = 0; i < len; i++) {
  70663. var bone = bones[i];
  70664. var points = this._debugLines[i];
  70665. if (!points) {
  70666. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  70667. this._debugLines[i] = points;
  70668. }
  70669. this._getBonePosition(points[0], bone, meshMat);
  70670. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  70671. points[0].subtractInPlace(meshPos);
  70672. points[1].subtractInPlace(meshPos);
  70673. }
  70674. };
  70675. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  70676. var len = bones.length;
  70677. var boneNum = 0;
  70678. var meshPos = this.mesh.position;
  70679. for (var i = len - 1; i >= 0; i--) {
  70680. var childBone = bones[i];
  70681. var parentBone = childBone.getParent();
  70682. if (!parentBone) {
  70683. continue;
  70684. }
  70685. var points = this._debugLines[boneNum];
  70686. if (!points) {
  70687. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  70688. this._debugLines[boneNum] = points;
  70689. }
  70690. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  70691. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  70692. points[0].subtractInPlace(meshPos);
  70693. points[1].subtractInPlace(meshPos);
  70694. boneNum++;
  70695. }
  70696. };
  70697. SkeletonViewer.prototype.update = function () {
  70698. if (this.autoUpdateBonesMatrices) {
  70699. this.skeleton.computeAbsoluteTransforms();
  70700. }
  70701. if (this.skeleton.bones[0].length === undefined) {
  70702. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  70703. }
  70704. else {
  70705. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  70706. }
  70707. if (!this._debugMesh) {
  70708. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  70709. this._debugMesh.renderingGroupId = this.renderingGroupId;
  70710. }
  70711. else {
  70712. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  70713. }
  70714. this._debugMesh.position.copyFrom(this.mesh.position);
  70715. this._debugMesh.color = this.color;
  70716. };
  70717. SkeletonViewer.prototype.dispose = function () {
  70718. if (this._debugMesh) {
  70719. this.isEnabled = false;
  70720. this._debugMesh.dispose();
  70721. this._debugMesh = null;
  70722. }
  70723. };
  70724. return SkeletonViewer;
  70725. }());
  70726. Debug.SkeletonViewer = SkeletonViewer;
  70727. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  70728. })(BABYLON || (BABYLON = {}));
  70729. //# sourceMappingURL=babylon.skeletonViewer.js.map
  70730. var BABYLON;
  70731. (function (BABYLON) {
  70732. var Debug;
  70733. (function (Debug) {
  70734. var AxesViewer = /** @class */ (function () {
  70735. function AxesViewer(scene, scaleLines) {
  70736. if (scaleLines === void 0) { scaleLines = 1; }
  70737. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  70738. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  70739. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  70740. this.scaleLines = 1;
  70741. this.scaleLines = scaleLines;
  70742. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  70743. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  70744. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  70745. this._xmesh.renderingGroupId = 2;
  70746. this._ymesh.renderingGroupId = 2;
  70747. this._zmesh.renderingGroupId = 2;
  70748. this._xmesh.material.checkReadyOnlyOnce = true;
  70749. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  70750. this._ymesh.material.checkReadyOnlyOnce = true;
  70751. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  70752. this._zmesh.material.checkReadyOnlyOnce = true;
  70753. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  70754. this.scene = scene;
  70755. }
  70756. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  70757. var scaleLines = this.scaleLines;
  70758. if (this._xmesh) {
  70759. this._xmesh.position.copyFrom(position);
  70760. }
  70761. if (this._ymesh) {
  70762. this._ymesh.position.copyFrom(position);
  70763. }
  70764. if (this._zmesh) {
  70765. this._zmesh.position.copyFrom(position);
  70766. }
  70767. var point2 = this._xline[1];
  70768. point2.x = xaxis.x * scaleLines;
  70769. point2.y = xaxis.y * scaleLines;
  70770. point2.z = xaxis.z * scaleLines;
  70771. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  70772. point2 = this._yline[1];
  70773. point2.x = yaxis.x * scaleLines;
  70774. point2.y = yaxis.y * scaleLines;
  70775. point2.z = yaxis.z * scaleLines;
  70776. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  70777. point2 = this._zline[1];
  70778. point2.x = zaxis.x * scaleLines;
  70779. point2.y = zaxis.y * scaleLines;
  70780. point2.z = zaxis.z * scaleLines;
  70781. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  70782. };
  70783. AxesViewer.prototype.dispose = function () {
  70784. if (this._xmesh) {
  70785. this._xmesh.dispose();
  70786. }
  70787. if (this._ymesh) {
  70788. this._ymesh.dispose();
  70789. }
  70790. if (this._zmesh) {
  70791. this._zmesh.dispose();
  70792. }
  70793. this._xmesh = null;
  70794. this._ymesh = null;
  70795. this._zmesh = null;
  70796. this.scene = null;
  70797. };
  70798. return AxesViewer;
  70799. }());
  70800. Debug.AxesViewer = AxesViewer;
  70801. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  70802. })(BABYLON || (BABYLON = {}));
  70803. //# sourceMappingURL=babylon.axesViewer.js.map
  70804. var BABYLON;
  70805. (function (BABYLON) {
  70806. var Debug;
  70807. (function (Debug) {
  70808. var BoneAxesViewer = /** @class */ (function (_super) {
  70809. __extends(BoneAxesViewer, _super);
  70810. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  70811. if (scaleLines === void 0) { scaleLines = 1; }
  70812. var _this = _super.call(this, scene, scaleLines) || this;
  70813. _this.pos = BABYLON.Vector3.Zero();
  70814. _this.xaxis = BABYLON.Vector3.Zero();
  70815. _this.yaxis = BABYLON.Vector3.Zero();
  70816. _this.zaxis = BABYLON.Vector3.Zero();
  70817. _this.mesh = mesh;
  70818. _this.bone = bone;
  70819. return _this;
  70820. }
  70821. BoneAxesViewer.prototype.update = function () {
  70822. if (!this.mesh || !this.bone) {
  70823. return;
  70824. }
  70825. var bone = this.bone;
  70826. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  70827. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  70828. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  70829. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  70830. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  70831. };
  70832. BoneAxesViewer.prototype.dispose = function () {
  70833. if (this.mesh) {
  70834. this.mesh = null;
  70835. this.bone = null;
  70836. _super.prototype.dispose.call(this);
  70837. }
  70838. };
  70839. return BoneAxesViewer;
  70840. }(Debug.AxesViewer));
  70841. Debug.BoneAxesViewer = BoneAxesViewer;
  70842. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  70843. })(BABYLON || (BABYLON = {}));
  70844. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  70845. var BABYLON;
  70846. (function (BABYLON) {
  70847. var RayHelper = /** @class */ (function () {
  70848. function RayHelper(ray) {
  70849. this.ray = ray;
  70850. }
  70851. RayHelper.CreateAndShow = function (ray, scene, color) {
  70852. var helper = new RayHelper(ray);
  70853. helper.show(scene, color);
  70854. return helper;
  70855. };
  70856. RayHelper.prototype.show = function (scene, color) {
  70857. if (!this._renderFunction && this.ray) {
  70858. var ray = this.ray;
  70859. this._renderFunction = this._render.bind(this);
  70860. this._scene = scene;
  70861. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  70862. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  70863. if (this._renderFunction) {
  70864. this._scene.registerBeforeRender(this._renderFunction);
  70865. }
  70866. }
  70867. if (color && this._renderLine) {
  70868. this._renderLine.color.copyFrom(color);
  70869. }
  70870. };
  70871. RayHelper.prototype.hide = function () {
  70872. if (this._renderFunction && this._scene) {
  70873. this._scene.unregisterBeforeRender(this._renderFunction);
  70874. this._scene = null;
  70875. this._renderFunction = null;
  70876. if (this._renderLine) {
  70877. this._renderLine.dispose();
  70878. this._renderLine = null;
  70879. }
  70880. this._renderPoints = [];
  70881. }
  70882. };
  70883. RayHelper.prototype._render = function () {
  70884. var ray = this.ray;
  70885. if (!ray) {
  70886. return;
  70887. }
  70888. var point = this._renderPoints[1];
  70889. var len = Math.min(ray.length, 1000000);
  70890. point.copyFrom(ray.direction);
  70891. point.scaleInPlace(len);
  70892. point.addInPlace(ray.origin);
  70893. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  70894. };
  70895. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  70896. this._attachedToMesh = mesh;
  70897. var ray = this.ray;
  70898. if (!ray) {
  70899. return;
  70900. }
  70901. if (!ray.direction) {
  70902. ray.direction = BABYLON.Vector3.Zero();
  70903. }
  70904. if (!ray.origin) {
  70905. ray.origin = BABYLON.Vector3.Zero();
  70906. }
  70907. if (length) {
  70908. ray.length = length;
  70909. }
  70910. if (!meshSpaceOrigin) {
  70911. meshSpaceOrigin = BABYLON.Vector3.Zero();
  70912. }
  70913. if (!meshSpaceDirection) {
  70914. // -1 so that this will work with Mesh.lookAt
  70915. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  70916. }
  70917. if (!this._meshSpaceDirection) {
  70918. this._meshSpaceDirection = meshSpaceDirection.clone();
  70919. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  70920. }
  70921. else {
  70922. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  70923. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  70924. }
  70925. if (!this._updateToMeshFunction) {
  70926. this._updateToMeshFunction = this._updateToMesh.bind(this);
  70927. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  70928. }
  70929. this._updateToMesh();
  70930. };
  70931. RayHelper.prototype.detachFromMesh = function () {
  70932. if (this._attachedToMesh) {
  70933. if (this._updateToMeshFunction) {
  70934. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  70935. }
  70936. this._attachedToMesh = null;
  70937. this._updateToMeshFunction = null;
  70938. }
  70939. };
  70940. RayHelper.prototype._updateToMesh = function () {
  70941. var ray = this.ray;
  70942. if (!this._attachedToMesh || !ray) {
  70943. return;
  70944. }
  70945. if (this._attachedToMesh._isDisposed) {
  70946. this.detachFromMesh();
  70947. return;
  70948. }
  70949. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  70950. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  70951. };
  70952. RayHelper.prototype.dispose = function () {
  70953. this.hide();
  70954. this.detachFromMesh();
  70955. this.ray = null;
  70956. };
  70957. return RayHelper;
  70958. }());
  70959. BABYLON.RayHelper = RayHelper;
  70960. })(BABYLON || (BABYLON = {}));
  70961. //# sourceMappingURL=babylon.rayHelper.js.map
  70962. var BABYLON;
  70963. (function (BABYLON) {
  70964. // load the inspector using require, if not present in the global namespace.
  70965. var DebugLayer = /** @class */ (function () {
  70966. function DebugLayer(scene) {
  70967. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  70968. this._scene = scene;
  70969. // load inspector using require, if it doesn't exist on the global namespace.
  70970. }
  70971. /** Creates the inspector window. */
  70972. DebugLayer.prototype._createInspector = function (config) {
  70973. if (config === void 0) { config = {}; }
  70974. var popup = config.popup || false;
  70975. var initialTab = config.initialTab || 0;
  70976. var parentElement = config.parentElement || null;
  70977. if (!this._inspector) {
  70978. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  70979. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  70980. } // else nothing to do,; instance is already existing
  70981. };
  70982. DebugLayer.prototype.isVisible = function () {
  70983. if (!this._inspector) {
  70984. return false;
  70985. }
  70986. return true;
  70987. };
  70988. DebugLayer.prototype.hide = function () {
  70989. if (this._inspector) {
  70990. try {
  70991. this._inspector.dispose();
  70992. }
  70993. catch (e) {
  70994. // If the inspector has been removed directly from the inspector tool
  70995. }
  70996. this._inspector = null;
  70997. }
  70998. };
  70999. DebugLayer.prototype.show = function (config) {
  71000. if (config === void 0) { config = {}; }
  71001. if (typeof this.BJSINSPECTOR == 'undefined') {
  71002. // Load inspector and add it to the DOM
  71003. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  71004. }
  71005. else {
  71006. // Otherwise creates the inspector
  71007. this._createInspector(config);
  71008. }
  71009. };
  71010. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  71011. return DebugLayer;
  71012. }());
  71013. BABYLON.DebugLayer = DebugLayer;
  71014. })(BABYLON || (BABYLON = {}));
  71015. //# sourceMappingURL=babylon.debugLayer.js.map
  71016. var BABYLON;
  71017. (function (BABYLON) {
  71018. var Debug;
  71019. (function (Debug) {
  71020. var PhysicsViewer = /** @class */ (function () {
  71021. function PhysicsViewer(scene) {
  71022. this._impostors = [];
  71023. this._meshes = [];
  71024. this._numMeshes = 0;
  71025. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  71026. var physicEngine = this._scene.getPhysicsEngine();
  71027. if (physicEngine) {
  71028. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  71029. }
  71030. }
  71031. PhysicsViewer.prototype._updateDebugMeshes = function () {
  71032. var plugin = this._physicsEnginePlugin;
  71033. for (var i = 0; i < this._numMeshes; i++) {
  71034. var impostor = this._impostors[i];
  71035. if (!impostor) {
  71036. continue;
  71037. }
  71038. if (impostor.isDisposed) {
  71039. this.hideImpostor(this._impostors[i--]);
  71040. }
  71041. else {
  71042. var mesh = this._meshes[i];
  71043. if (mesh && plugin) {
  71044. plugin.syncMeshWithImpostor(mesh, impostor);
  71045. }
  71046. }
  71047. }
  71048. };
  71049. PhysicsViewer.prototype.showImpostor = function (impostor) {
  71050. if (!this._scene) {
  71051. return;
  71052. }
  71053. for (var i = 0; i < this._numMeshes; i++) {
  71054. if (this._impostors[i] == impostor) {
  71055. return;
  71056. }
  71057. }
  71058. var debugMesh = this._getDebugMesh(impostor, this._scene);
  71059. if (debugMesh) {
  71060. this._impostors[this._numMeshes] = impostor;
  71061. this._meshes[this._numMeshes] = debugMesh;
  71062. if (this._numMeshes === 0) {
  71063. this._renderFunction = this._updateDebugMeshes.bind(this);
  71064. this._scene.registerBeforeRender(this._renderFunction);
  71065. }
  71066. this._numMeshes++;
  71067. }
  71068. };
  71069. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  71070. if (!impostor || !this._scene) {
  71071. return;
  71072. }
  71073. var removed = false;
  71074. for (var i = 0; i < this._numMeshes; i++) {
  71075. if (this._impostors[i] == impostor) {
  71076. var mesh = this._meshes[i];
  71077. if (!mesh) {
  71078. continue;
  71079. }
  71080. this._scene.removeMesh(mesh);
  71081. mesh.dispose();
  71082. this._numMeshes--;
  71083. if (this._numMeshes > 0) {
  71084. this._meshes[i] = this._meshes[this._numMeshes];
  71085. this._impostors[i] = this._impostors[this._numMeshes];
  71086. this._meshes[this._numMeshes] = null;
  71087. this._impostors[this._numMeshes] = null;
  71088. }
  71089. else {
  71090. this._meshes[0] = null;
  71091. this._impostors[0] = null;
  71092. }
  71093. removed = true;
  71094. break;
  71095. }
  71096. }
  71097. if (removed && this._numMeshes === 0) {
  71098. this._scene.unregisterBeforeRender(this._renderFunction);
  71099. }
  71100. };
  71101. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  71102. if (!this._debugMaterial) {
  71103. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  71104. this._debugMaterial.wireframe = true;
  71105. }
  71106. return this._debugMaterial;
  71107. };
  71108. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  71109. if (!this._debugBoxMesh) {
  71110. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  71111. this._debugBoxMesh.renderingGroupId = 1;
  71112. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  71113. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  71114. scene.removeMesh(this._debugBoxMesh);
  71115. }
  71116. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  71117. };
  71118. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  71119. if (!this._debugSphereMesh) {
  71120. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  71121. this._debugSphereMesh.renderingGroupId = 1;
  71122. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  71123. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  71124. scene.removeMesh(this._debugSphereMesh);
  71125. }
  71126. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  71127. };
  71128. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  71129. var mesh = null;
  71130. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  71131. mesh = this._getDebugBoxMesh(scene);
  71132. impostor.getBoxSizeToRef(mesh.scaling);
  71133. }
  71134. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  71135. mesh = this._getDebugSphereMesh(scene);
  71136. var radius = impostor.getRadius();
  71137. mesh.scaling.x = radius * 2;
  71138. mesh.scaling.y = radius * 2;
  71139. mesh.scaling.z = radius * 2;
  71140. }
  71141. return mesh;
  71142. };
  71143. PhysicsViewer.prototype.dispose = function () {
  71144. for (var i = 0; i < this._numMeshes; i++) {
  71145. this.hideImpostor(this._impostors[i]);
  71146. }
  71147. if (this._debugBoxMesh) {
  71148. this._debugBoxMesh.dispose();
  71149. }
  71150. if (this._debugSphereMesh) {
  71151. this._debugSphereMesh.dispose();
  71152. }
  71153. if (this._debugMaterial) {
  71154. this._debugMaterial.dispose();
  71155. }
  71156. this._impostors.length = 0;
  71157. this._scene = null;
  71158. this._physicsEnginePlugin = null;
  71159. };
  71160. return PhysicsViewer;
  71161. }());
  71162. Debug.PhysicsViewer = PhysicsViewer;
  71163. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  71164. })(BABYLON || (BABYLON = {}));
  71165. //# sourceMappingURL=babylon.physicsViewer.js.map
  71166. var BABYLON;
  71167. (function (BABYLON) {
  71168. var BoundingBoxRenderer = /** @class */ (function () {
  71169. function BoundingBoxRenderer(scene) {
  71170. this.frontColor = new BABYLON.Color3(1, 1, 1);
  71171. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  71172. this.showBackLines = true;
  71173. this.renderList = new BABYLON.SmartArray(32);
  71174. this._vertexBuffers = {};
  71175. this._scene = scene;
  71176. }
  71177. BoundingBoxRenderer.prototype._prepareRessources = function () {
  71178. if (this._colorShader) {
  71179. return;
  71180. }
  71181. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  71182. attributes: [BABYLON.VertexBuffer.PositionKind],
  71183. uniforms: ["world", "viewProjection", "color"]
  71184. });
  71185. var engine = this._scene.getEngine();
  71186. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  71187. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  71188. this._createIndexBuffer();
  71189. };
  71190. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  71191. var engine = this._scene.getEngine();
  71192. 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]);
  71193. };
  71194. BoundingBoxRenderer.prototype._rebuild = function () {
  71195. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71196. if (vb) {
  71197. vb._rebuild();
  71198. }
  71199. this._createIndexBuffer();
  71200. };
  71201. BoundingBoxRenderer.prototype.reset = function () {
  71202. this.renderList.reset();
  71203. };
  71204. BoundingBoxRenderer.prototype.render = function () {
  71205. if (this.renderList.length === 0) {
  71206. return;
  71207. }
  71208. this._prepareRessources();
  71209. if (!this._colorShader.isReady()) {
  71210. return;
  71211. }
  71212. var engine = this._scene.getEngine();
  71213. engine.setDepthWrite(false);
  71214. this._colorShader._preBind();
  71215. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  71216. var boundingBox = this.renderList.data[boundingBoxIndex];
  71217. var min = boundingBox.minimum;
  71218. var max = boundingBox.maximum;
  71219. var diff = max.subtract(min);
  71220. var median = min.add(diff.scale(0.5));
  71221. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  71222. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  71223. .multiply(boundingBox.getWorldMatrix());
  71224. // VBOs
  71225. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  71226. if (this.showBackLines) {
  71227. // Back
  71228. engine.setDepthFunctionToGreaterOrEqual();
  71229. this._scene.resetCachedMaterial();
  71230. this._colorShader.setColor4("color", this.backColor.toColor4());
  71231. this._colorShader.bind(worldMatrix);
  71232. // Draw order
  71233. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  71234. }
  71235. // Front
  71236. engine.setDepthFunctionToLess();
  71237. this._scene.resetCachedMaterial();
  71238. this._colorShader.setColor4("color", this.frontColor.toColor4());
  71239. this._colorShader.bind(worldMatrix);
  71240. // Draw order
  71241. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  71242. }
  71243. this._colorShader.unbind();
  71244. engine.setDepthFunctionToLessOrEqual();
  71245. engine.setDepthWrite(true);
  71246. };
  71247. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  71248. this._prepareRessources();
  71249. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  71250. return;
  71251. }
  71252. var engine = this._scene.getEngine();
  71253. engine.setDepthWrite(false);
  71254. engine.setColorWrite(false);
  71255. this._colorShader._preBind();
  71256. var boundingBox = mesh._boundingInfo.boundingBox;
  71257. var min = boundingBox.minimum;
  71258. var max = boundingBox.maximum;
  71259. var diff = max.subtract(min);
  71260. var median = min.add(diff.scale(0.5));
  71261. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  71262. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  71263. .multiply(boundingBox.getWorldMatrix());
  71264. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  71265. engine.setDepthFunctionToLess();
  71266. this._scene.resetCachedMaterial();
  71267. this._colorShader.bind(worldMatrix);
  71268. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 24);
  71269. this._colorShader.unbind();
  71270. engine.setDepthFunctionToLessOrEqual();
  71271. engine.setDepthWrite(true);
  71272. engine.setColorWrite(true);
  71273. };
  71274. BoundingBoxRenderer.prototype.dispose = function () {
  71275. if (!this._colorShader) {
  71276. return;
  71277. }
  71278. this.renderList.dispose();
  71279. this._colorShader.dispose();
  71280. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71281. if (buffer) {
  71282. buffer.dispose();
  71283. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  71284. }
  71285. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  71286. };
  71287. return BoundingBoxRenderer;
  71288. }());
  71289. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  71290. })(BABYLON || (BABYLON = {}));
  71291. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  71292. var BABYLON;
  71293. (function (BABYLON) {
  71294. var MorphTarget = /** @class */ (function () {
  71295. function MorphTarget(name, influence) {
  71296. if (influence === void 0) { influence = 0; }
  71297. this.name = name;
  71298. this.animations = new Array();
  71299. this._positions = null;
  71300. this._normals = null;
  71301. this._tangents = null;
  71302. this.onInfluenceChanged = new BABYLON.Observable();
  71303. this.influence = influence;
  71304. }
  71305. Object.defineProperty(MorphTarget.prototype, "influence", {
  71306. get: function () {
  71307. return this._influence;
  71308. },
  71309. set: function (influence) {
  71310. if (this._influence === influence) {
  71311. return;
  71312. }
  71313. var previous = this._influence;
  71314. this._influence = influence;
  71315. if (this.onInfluenceChanged.hasObservers) {
  71316. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  71317. }
  71318. },
  71319. enumerable: true,
  71320. configurable: true
  71321. });
  71322. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  71323. get: function () {
  71324. return !!this._positions;
  71325. },
  71326. enumerable: true,
  71327. configurable: true
  71328. });
  71329. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  71330. get: function () {
  71331. return !!this._normals;
  71332. },
  71333. enumerable: true,
  71334. configurable: true
  71335. });
  71336. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  71337. get: function () {
  71338. return !!this._tangents;
  71339. },
  71340. enumerable: true,
  71341. configurable: true
  71342. });
  71343. MorphTarget.prototype.setPositions = function (data) {
  71344. this._positions = data;
  71345. };
  71346. MorphTarget.prototype.getPositions = function () {
  71347. return this._positions;
  71348. };
  71349. MorphTarget.prototype.setNormals = function (data) {
  71350. this._normals = data;
  71351. };
  71352. MorphTarget.prototype.getNormals = function () {
  71353. return this._normals;
  71354. };
  71355. MorphTarget.prototype.setTangents = function (data) {
  71356. this._tangents = data;
  71357. };
  71358. MorphTarget.prototype.getTangents = function () {
  71359. return this._tangents;
  71360. };
  71361. /**
  71362. * Serializes the current target into a Serialization object.
  71363. * Returns the serialized object.
  71364. */
  71365. MorphTarget.prototype.serialize = function () {
  71366. var serializationObject = {};
  71367. serializationObject.name = this.name;
  71368. serializationObject.influence = this.influence;
  71369. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  71370. if (this.hasNormals) {
  71371. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  71372. }
  71373. if (this.hasTangents) {
  71374. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  71375. }
  71376. // Animations
  71377. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  71378. return serializationObject;
  71379. };
  71380. // Statics
  71381. MorphTarget.Parse = function (serializationObject) {
  71382. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  71383. result.setPositions(serializationObject.positions);
  71384. if (serializationObject.normals) {
  71385. result.setNormals(serializationObject.normals);
  71386. }
  71387. if (serializationObject.tangents) {
  71388. result.setTangents(serializationObject.tangents);
  71389. }
  71390. // Animations
  71391. if (serializationObject.animations) {
  71392. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  71393. var parsedAnimation = serializationObject.animations[animationIndex];
  71394. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  71395. }
  71396. }
  71397. return result;
  71398. };
  71399. MorphTarget.FromMesh = function (mesh, name, influence) {
  71400. if (!name) {
  71401. name = mesh.name;
  71402. }
  71403. var result = new MorphTarget(name, influence);
  71404. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  71405. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  71406. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  71407. }
  71408. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  71409. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  71410. }
  71411. return result;
  71412. };
  71413. return MorphTarget;
  71414. }());
  71415. BABYLON.MorphTarget = MorphTarget;
  71416. })(BABYLON || (BABYLON = {}));
  71417. //# sourceMappingURL=babylon.morphTarget.js.map
  71418. var BABYLON;
  71419. (function (BABYLON) {
  71420. var MorphTargetManager = /** @class */ (function () {
  71421. function MorphTargetManager(scene) {
  71422. if (scene === void 0) { scene = null; }
  71423. this._targets = new Array();
  71424. this._targetObservable = new Array();
  71425. this._activeTargets = new BABYLON.SmartArray(16);
  71426. this._supportsNormals = false;
  71427. this._supportsTangents = false;
  71428. this._vertexCount = 0;
  71429. this._uniqueId = 0;
  71430. this._tempInfluences = new Array();
  71431. if (!scene) {
  71432. scene = BABYLON.Engine.LastCreatedScene;
  71433. }
  71434. this._scene = scene;
  71435. if (this._scene) {
  71436. this._scene.morphTargetManagers.push(this);
  71437. this._uniqueId = this._scene.getUniqueId();
  71438. }
  71439. }
  71440. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  71441. get: function () {
  71442. return this._uniqueId;
  71443. },
  71444. enumerable: true,
  71445. configurable: true
  71446. });
  71447. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  71448. get: function () {
  71449. return this._vertexCount;
  71450. },
  71451. enumerable: true,
  71452. configurable: true
  71453. });
  71454. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  71455. get: function () {
  71456. return this._supportsNormals;
  71457. },
  71458. enumerable: true,
  71459. configurable: true
  71460. });
  71461. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  71462. get: function () {
  71463. return this._supportsTangents;
  71464. },
  71465. enumerable: true,
  71466. configurable: true
  71467. });
  71468. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  71469. get: function () {
  71470. return this._targets.length;
  71471. },
  71472. enumerable: true,
  71473. configurable: true
  71474. });
  71475. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  71476. get: function () {
  71477. return this._activeTargets.length;
  71478. },
  71479. enumerable: true,
  71480. configurable: true
  71481. });
  71482. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  71483. get: function () {
  71484. return this._influences;
  71485. },
  71486. enumerable: true,
  71487. configurable: true
  71488. });
  71489. MorphTargetManager.prototype.getActiveTarget = function (index) {
  71490. return this._activeTargets.data[index];
  71491. };
  71492. MorphTargetManager.prototype.getTarget = function (index) {
  71493. return this._targets[index];
  71494. };
  71495. MorphTargetManager.prototype.addTarget = function (target) {
  71496. var _this = this;
  71497. this._targets.push(target);
  71498. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  71499. _this._syncActiveTargets(needUpdate);
  71500. }));
  71501. this._syncActiveTargets(true);
  71502. };
  71503. MorphTargetManager.prototype.removeTarget = function (target) {
  71504. var index = this._targets.indexOf(target);
  71505. if (index >= 0) {
  71506. this._targets.splice(index, 1);
  71507. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  71508. this._syncActiveTargets(true);
  71509. }
  71510. };
  71511. /**
  71512. * Serializes the current manager into a Serialization object.
  71513. * Returns the serialized object.
  71514. */
  71515. MorphTargetManager.prototype.serialize = function () {
  71516. var serializationObject = {};
  71517. serializationObject.id = this.uniqueId;
  71518. serializationObject.targets = [];
  71519. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  71520. var target = _a[_i];
  71521. serializationObject.targets.push(target.serialize());
  71522. }
  71523. return serializationObject;
  71524. };
  71525. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  71526. var influenceCount = 0;
  71527. this._activeTargets.reset();
  71528. this._supportsNormals = true;
  71529. this._supportsTangents = true;
  71530. this._vertexCount = 0;
  71531. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  71532. var target = _a[_i];
  71533. if (target.influence > 0) {
  71534. this._activeTargets.push(target);
  71535. this._tempInfluences[influenceCount++] = target.influence;
  71536. this._supportsNormals = this._supportsNormals && target.hasNormals;
  71537. this._supportsTangents = this._supportsTangents && target.hasTangents;
  71538. var positions = target.getPositions();
  71539. if (!positions) {
  71540. BABYLON.Tools.Error("Invalid target. Target must positions.");
  71541. return;
  71542. }
  71543. var vertexCount = positions.length / 3;
  71544. if (this._vertexCount === 0) {
  71545. this._vertexCount = vertexCount;
  71546. }
  71547. else if (this._vertexCount !== vertexCount) {
  71548. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  71549. return;
  71550. }
  71551. }
  71552. }
  71553. if (!this._influences || this._influences.length !== influenceCount) {
  71554. this._influences = new Float32Array(influenceCount);
  71555. }
  71556. for (var index = 0; index < influenceCount; index++) {
  71557. this._influences[index] = this._tempInfluences[index];
  71558. }
  71559. if (needUpdate && this._scene) {
  71560. // Flag meshes as dirty to resync with the active targets
  71561. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  71562. var mesh = _c[_b];
  71563. if (mesh.morphTargetManager === this) {
  71564. mesh._syncGeometryWithMorphTargetManager();
  71565. }
  71566. }
  71567. }
  71568. };
  71569. // Statics
  71570. MorphTargetManager.Parse = function (serializationObject, scene) {
  71571. var result = new MorphTargetManager(scene);
  71572. result._uniqueId = serializationObject.id;
  71573. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  71574. var targetData = _a[_i];
  71575. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  71576. }
  71577. return result;
  71578. };
  71579. return MorphTargetManager;
  71580. }());
  71581. BABYLON.MorphTargetManager = MorphTargetManager;
  71582. })(BABYLON || (BABYLON = {}));
  71583. //# sourceMappingURL=babylon.morphTargetManager.js.map
  71584. var BABYLON;
  71585. (function (BABYLON) {
  71586. var Octree = /** @class */ (function () {
  71587. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  71588. if (maxDepth === void 0) { maxDepth = 2; }
  71589. this.maxDepth = maxDepth;
  71590. this.dynamicContent = new Array();
  71591. this._maxBlockCapacity = maxBlockCapacity || 64;
  71592. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  71593. this._creationFunc = creationFunc;
  71594. }
  71595. // Methods
  71596. Octree.prototype.update = function (worldMin, worldMax, entries) {
  71597. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  71598. };
  71599. Octree.prototype.addMesh = function (entry) {
  71600. for (var index = 0; index < this.blocks.length; index++) {
  71601. var block = this.blocks[index];
  71602. block.addEntry(entry);
  71603. }
  71604. };
  71605. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  71606. this._selectionContent.reset();
  71607. for (var index = 0; index < this.blocks.length; index++) {
  71608. var block = this.blocks[index];
  71609. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  71610. }
  71611. if (allowDuplicate) {
  71612. this._selectionContent.concat(this.dynamicContent);
  71613. }
  71614. else {
  71615. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  71616. }
  71617. return this._selectionContent;
  71618. };
  71619. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  71620. this._selectionContent.reset();
  71621. for (var index = 0; index < this.blocks.length; index++) {
  71622. var block = this.blocks[index];
  71623. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  71624. }
  71625. if (allowDuplicate) {
  71626. this._selectionContent.concat(this.dynamicContent);
  71627. }
  71628. else {
  71629. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  71630. }
  71631. return this._selectionContent;
  71632. };
  71633. Octree.prototype.intersectsRay = function (ray) {
  71634. this._selectionContent.reset();
  71635. for (var index = 0; index < this.blocks.length; index++) {
  71636. var block = this.blocks[index];
  71637. block.intersectsRay(ray, this._selectionContent);
  71638. }
  71639. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  71640. return this._selectionContent;
  71641. };
  71642. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  71643. target.blocks = new Array();
  71644. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  71645. // Segmenting space
  71646. for (var x = 0; x < 2; x++) {
  71647. for (var y = 0; y < 2; y++) {
  71648. for (var z = 0; z < 2; z++) {
  71649. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  71650. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  71651. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  71652. block.addEntries(entries);
  71653. target.blocks.push(block);
  71654. }
  71655. }
  71656. }
  71657. };
  71658. Octree.CreationFuncForMeshes = function (entry, block) {
  71659. var boundingInfo = entry.getBoundingInfo();
  71660. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  71661. block.entries.push(entry);
  71662. }
  71663. };
  71664. Octree.CreationFuncForSubMeshes = function (entry, block) {
  71665. var boundingInfo = entry.getBoundingInfo();
  71666. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  71667. block.entries.push(entry);
  71668. }
  71669. };
  71670. return Octree;
  71671. }());
  71672. BABYLON.Octree = Octree;
  71673. })(BABYLON || (BABYLON = {}));
  71674. //# sourceMappingURL=babylon.octree.js.map
  71675. var BABYLON;
  71676. (function (BABYLON) {
  71677. var OctreeBlock = /** @class */ (function () {
  71678. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  71679. this.entries = new Array();
  71680. this._boundingVectors = new Array();
  71681. this._capacity = capacity;
  71682. this._depth = depth;
  71683. this._maxDepth = maxDepth;
  71684. this._creationFunc = creationFunc;
  71685. this._minPoint = minPoint;
  71686. this._maxPoint = maxPoint;
  71687. this._boundingVectors.push(minPoint.clone());
  71688. this._boundingVectors.push(maxPoint.clone());
  71689. this._boundingVectors.push(minPoint.clone());
  71690. this._boundingVectors[2].x = maxPoint.x;
  71691. this._boundingVectors.push(minPoint.clone());
  71692. this._boundingVectors[3].y = maxPoint.y;
  71693. this._boundingVectors.push(minPoint.clone());
  71694. this._boundingVectors[4].z = maxPoint.z;
  71695. this._boundingVectors.push(maxPoint.clone());
  71696. this._boundingVectors[5].z = minPoint.z;
  71697. this._boundingVectors.push(maxPoint.clone());
  71698. this._boundingVectors[6].x = minPoint.x;
  71699. this._boundingVectors.push(maxPoint.clone());
  71700. this._boundingVectors[7].y = minPoint.y;
  71701. }
  71702. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  71703. // Property
  71704. get: function () {
  71705. return this._capacity;
  71706. },
  71707. enumerable: true,
  71708. configurable: true
  71709. });
  71710. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  71711. get: function () {
  71712. return this._minPoint;
  71713. },
  71714. enumerable: true,
  71715. configurable: true
  71716. });
  71717. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  71718. get: function () {
  71719. return this._maxPoint;
  71720. },
  71721. enumerable: true,
  71722. configurable: true
  71723. });
  71724. // Methods
  71725. OctreeBlock.prototype.addEntry = function (entry) {
  71726. if (this.blocks) {
  71727. for (var index = 0; index < this.blocks.length; index++) {
  71728. var block = this.blocks[index];
  71729. block.addEntry(entry);
  71730. }
  71731. return;
  71732. }
  71733. this._creationFunc(entry, this);
  71734. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  71735. this.createInnerBlocks();
  71736. }
  71737. };
  71738. OctreeBlock.prototype.addEntries = function (entries) {
  71739. for (var index = 0; index < entries.length; index++) {
  71740. var mesh = entries[index];
  71741. this.addEntry(mesh);
  71742. }
  71743. };
  71744. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  71745. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  71746. if (this.blocks) {
  71747. for (var index = 0; index < this.blocks.length; index++) {
  71748. var block = this.blocks[index];
  71749. block.select(frustumPlanes, selection, allowDuplicate);
  71750. }
  71751. return;
  71752. }
  71753. if (allowDuplicate) {
  71754. selection.concat(this.entries);
  71755. }
  71756. else {
  71757. selection.concatWithNoDuplicate(this.entries);
  71758. }
  71759. }
  71760. };
  71761. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  71762. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  71763. if (this.blocks) {
  71764. for (var index = 0; index < this.blocks.length; index++) {
  71765. var block = this.blocks[index];
  71766. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  71767. }
  71768. return;
  71769. }
  71770. if (allowDuplicate) {
  71771. selection.concat(this.entries);
  71772. }
  71773. else {
  71774. selection.concatWithNoDuplicate(this.entries);
  71775. }
  71776. }
  71777. };
  71778. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  71779. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  71780. if (this.blocks) {
  71781. for (var index = 0; index < this.blocks.length; index++) {
  71782. var block = this.blocks[index];
  71783. block.intersectsRay(ray, selection);
  71784. }
  71785. return;
  71786. }
  71787. selection.concatWithNoDuplicate(this.entries);
  71788. }
  71789. };
  71790. OctreeBlock.prototype.createInnerBlocks = function () {
  71791. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  71792. };
  71793. return OctreeBlock;
  71794. }());
  71795. BABYLON.OctreeBlock = OctreeBlock;
  71796. })(BABYLON || (BABYLON = {}));
  71797. //# sourceMappingURL=babylon.octreeBlock.js.map
  71798. var BABYLON;
  71799. (function (BABYLON) {
  71800. var SIMDVector3 = /** @class */ (function () {
  71801. function SIMDVector3() {
  71802. }
  71803. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  71804. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  71805. };
  71806. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  71807. var m = transformation.m;
  71808. var m0 = SIMD.Float32x4.load(m, 0);
  71809. var m1 = SIMD.Float32x4.load(m, 4);
  71810. var m2 = SIMD.Float32x4.load(m, 8);
  71811. var m3 = SIMD.Float32x4.load(m, 12);
  71812. var r = SIMD.Float32x4.add(SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(x), m0), SIMD.Float32x4.mul(SIMD.Float32x4.splat(y), m1)), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(z), m2), m3));
  71813. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  71814. result.x = SIMD.Float32x4.extractLane(r, 0);
  71815. result.y = SIMD.Float32x4.extractLane(r, 1);
  71816. result.z = SIMD.Float32x4.extractLane(r, 2);
  71817. };
  71818. return SIMDVector3;
  71819. }());
  71820. var SIMDMatrix = /** @class */ (function () {
  71821. function SIMDMatrix() {
  71822. }
  71823. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  71824. var tm = this.m;
  71825. var om = other.m;
  71826. var m0 = SIMD.Float32x4.load(om, 0);
  71827. var m1 = SIMD.Float32x4.load(om, 4);
  71828. var m2 = SIMD.Float32x4.load(om, 8);
  71829. var m3 = SIMD.Float32x4.load(om, 12);
  71830. for (var i = 0; i < 16; i += 4) {
  71831. SIMD.Float32x4.store(result, i + offset, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i]), m0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 1]), m1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 2]), m2), SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 3]), m3)))));
  71832. }
  71833. return this;
  71834. };
  71835. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  71836. var src = this.m;
  71837. var dest = other.m;
  71838. // Load the 4 rows
  71839. var src0 = SIMD.Float32x4.load(src, 0);
  71840. var src1 = SIMD.Float32x4.load(src, 4);
  71841. var src2 = SIMD.Float32x4.load(src, 8);
  71842. var src3 = SIMD.Float32x4.load(src, 12);
  71843. // Transpose the source matrix. Sort of. Not a true transpose operation
  71844. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  71845. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  71846. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  71847. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  71848. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  71849. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  71850. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  71851. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  71852. // This is a true transposition, but it will lead to an incorrect result
  71853. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  71854. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  71855. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  71856. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  71857. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  71858. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  71859. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  71860. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  71861. // ----
  71862. tmp1 = SIMD.Float32x4.mul(row2, row3);
  71863. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  71864. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  71865. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  71866. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  71867. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  71868. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  71869. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  71870. // ----
  71871. tmp1 = SIMD.Float32x4.mul(row1, row2);
  71872. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  71873. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  71874. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  71875. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  71876. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  71877. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  71878. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  71879. // ----
  71880. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  71881. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  71882. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  71883. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  71884. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  71885. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  71886. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  71887. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  71888. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  71889. // ----
  71890. tmp1 = SIMD.Float32x4.mul(row0, row1);
  71891. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  71892. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  71893. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  71894. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  71895. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  71896. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  71897. // ----
  71898. tmp1 = SIMD.Float32x4.mul(row0, row3);
  71899. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  71900. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  71901. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  71902. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  71903. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  71904. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  71905. // ----
  71906. tmp1 = SIMD.Float32x4.mul(row0, row2);
  71907. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  71908. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  71909. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  71910. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  71911. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  71912. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  71913. // Compute determinant
  71914. var det = SIMD.Float32x4.mul(row0, minor0);
  71915. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  71916. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  71917. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  71918. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  71919. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  71920. // These shuffles aren't necessary if the faulty transposition is done
  71921. // up at the top of this function.
  71922. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  71923. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  71924. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  71925. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  71926. // Compute final values by multiplying with 1/det
  71927. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  71928. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  71929. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  71930. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  71931. return this;
  71932. };
  71933. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  71934. var out = result.m;
  71935. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  71936. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  71937. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  71938. // cc.kmVec3Subtract(f, pCenter, pEye);
  71939. var f = SIMD.Float32x4.sub(center, eye);
  71940. // cc.kmVec3Normalize(f, f);
  71941. var tmp = SIMD.Float32x4.mul(f, f);
  71942. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  71943. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  71944. // cc.kmVec3Assign(up, pUp);
  71945. // cc.kmVec3Normalize(up, up);
  71946. tmp = SIMD.Float32x4.mul(up, up);
  71947. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  71948. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  71949. // cc.kmVec3Cross(s, f, up);
  71950. var s = SIMD.Float32x4.sub(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(f, 1, 2, 0, 3), SIMD.Float32x4.swizzle(up, 2, 0, 1, 3)), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(f, 2, 0, 1, 3), SIMD.Float32x4.swizzle(up, 1, 2, 0, 3)));
  71951. // cc.kmVec3Normalize(s, s);
  71952. tmp = SIMD.Float32x4.mul(s, s);
  71953. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  71954. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  71955. // cc.kmVec3Cross(u, s, f);
  71956. var u = SIMD.Float32x4.sub(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(s, 1, 2, 0, 3), SIMD.Float32x4.swizzle(f, 2, 0, 1, 3)), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(s, 2, 0, 1, 3), SIMD.Float32x4.swizzle(f, 1, 2, 0, 3)));
  71957. // cc.kmVec3Normalize(s, s);
  71958. tmp = SIMD.Float32x4.mul(s, s);
  71959. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  71960. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  71961. var zero = SIMD.Float32x4.splat(0.0);
  71962. s = SIMD.Float32x4.neg(s);
  71963. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  71964. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  71965. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  71966. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  71967. var a2 = SIMD.Float32x4.shuffle(SIMD.Float32x4.shuffle(s, u, 2, 3, 6, 7), SIMD.Float32x4.shuffle(f, zero, 2, 3, 6, 7), 0, 2, 4, 6);
  71968. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  71969. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  71970. SIMD.Float32x4.store(out, 0, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  71971. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  71972. SIMD.Float32x4.store(out, 4, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  71973. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  71974. SIMD.Float32x4.store(out, 8, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  71975. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  71976. SIMD.Float32x4.store(out, 12, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  71977. };
  71978. return SIMDMatrix;
  71979. }());
  71980. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  71981. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  71982. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  71983. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  71984. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  71985. var SIMDHelper = /** @class */ (function () {
  71986. function SIMDHelper() {
  71987. }
  71988. Object.defineProperty(SIMDHelper, "IsEnabled", {
  71989. get: function () {
  71990. return SIMDHelper._isEnabled;
  71991. },
  71992. enumerable: true,
  71993. configurable: true
  71994. });
  71995. SIMDHelper.DisableSIMD = function () {
  71996. // Replace functions
  71997. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  71998. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  71999. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  72000. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  72001. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  72002. SIMDHelper._isEnabled = false;
  72003. };
  72004. SIMDHelper.EnableSIMD = function () {
  72005. if (self.SIMD === undefined) {
  72006. return;
  72007. }
  72008. // check if polyfills needed
  72009. if (!self.Math.fround) {
  72010. self.Math.fround = (function (array) { return function (x) {
  72011. return array[0] = x, array[0];
  72012. }; })(new Float32Array(1));
  72013. }
  72014. if (!self.Math.imul) {
  72015. self.Math.imul = function (a, b) {
  72016. var ah = (a >>> 16) & 0xffff;
  72017. var al = a & 0xffff;
  72018. var bh = (b >>> 16) & 0xffff;
  72019. var bl = b & 0xffff;
  72020. // the shift by 0 fixes the sign on the high part
  72021. // the final |0 converts the unsigned value into a signed value
  72022. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  72023. };
  72024. }
  72025. // Replace functions
  72026. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  72027. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  72028. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  72029. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  72030. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  72031. SIMDHelper._isEnabled = true;
  72032. };
  72033. SIMDHelper._isEnabled = false;
  72034. return SIMDHelper;
  72035. }());
  72036. BABYLON.SIMDHelper = SIMDHelper;
  72037. })(BABYLON || (BABYLON = {}));
  72038. //# sourceMappingURL=babylon.math.SIMD.js.map
  72039. var BABYLON;
  72040. (function (BABYLON) {
  72041. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  72042. __extends(VRDistortionCorrectionPostProcess, _super);
  72043. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  72044. var _this = _super.call(this, name, "vrDistortionCorrection", [
  72045. 'LensCenter',
  72046. 'Scale',
  72047. 'ScaleIn',
  72048. 'HmdWarpParam'
  72049. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  72050. _this._isRightEye = isRightEye;
  72051. _this._distortionFactors = vrMetrics.distortionK;
  72052. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  72053. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  72054. _this.adaptScaleToCurrentViewport = true;
  72055. _this.onSizeChangedObservable.add(function () {
  72056. _this.aspectRatio = _this.width * .5 / _this.height;
  72057. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  72058. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  72059. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  72060. });
  72061. _this.onApplyObservable.add(function (effect) {
  72062. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  72063. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  72064. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  72065. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  72066. });
  72067. return _this;
  72068. }
  72069. return VRDistortionCorrectionPostProcess;
  72070. }(BABYLON.PostProcess));
  72071. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  72072. })(BABYLON || (BABYLON = {}));
  72073. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  72074. var BABYLON;
  72075. (function (BABYLON) {
  72076. var AnaglyphPostProcess = /** @class */ (function (_super) {
  72077. __extends(AnaglyphPostProcess, _super);
  72078. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  72079. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  72080. _this._passedProcess = rigCameras[0]._rigPostProcess;
  72081. _this.onApplyObservable.add(function (effect) {
  72082. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  72083. });
  72084. return _this;
  72085. }
  72086. return AnaglyphPostProcess;
  72087. }(BABYLON.PostProcess));
  72088. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  72089. })(BABYLON || (BABYLON = {}));
  72090. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  72091. var BABYLON;
  72092. (function (BABYLON) {
  72093. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  72094. __extends(StereoscopicInterlacePostProcess, _super);
  72095. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  72096. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  72097. _this._passedProcess = rigCameras[0]._rigPostProcess;
  72098. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  72099. _this.onSizeChangedObservable.add(function () {
  72100. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  72101. });
  72102. _this.onApplyObservable.add(function (effect) {
  72103. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  72104. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  72105. });
  72106. return _this;
  72107. }
  72108. return StereoscopicInterlacePostProcess;
  72109. }(BABYLON.PostProcess));
  72110. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  72111. })(BABYLON || (BABYLON = {}));
  72112. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  72113. var BABYLON;
  72114. (function (BABYLON) {
  72115. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  72116. function FreeCameraDeviceOrientationInput() {
  72117. var _this = this;
  72118. this._screenOrientationAngle = 0;
  72119. this._screenQuaternion = new BABYLON.Quaternion();
  72120. this._alpha = 0;
  72121. this._beta = 0;
  72122. this._gamma = 0;
  72123. this._orientationChanged = function () {
  72124. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  72125. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  72126. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  72127. };
  72128. this._deviceOrientation = function (evt) {
  72129. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  72130. _this._beta = evt.beta !== null ? evt.beta : 0;
  72131. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  72132. };
  72133. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  72134. this._orientationChanged();
  72135. }
  72136. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  72137. get: function () {
  72138. return this._camera;
  72139. },
  72140. set: function (camera) {
  72141. this._camera = camera;
  72142. if (this._camera != null && !this._camera.rotationQuaternion) {
  72143. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  72144. }
  72145. },
  72146. enumerable: true,
  72147. configurable: true
  72148. });
  72149. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  72150. window.addEventListener("orientationchange", this._orientationChanged);
  72151. window.addEventListener("deviceorientation", this._deviceOrientation);
  72152. //In certain cases, the attach control is called AFTER orientation was changed,
  72153. //So this is needed.
  72154. this._orientationChanged();
  72155. };
  72156. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  72157. window.removeEventListener("orientationchange", this._orientationChanged);
  72158. window.removeEventListener("deviceorientation", this._deviceOrientation);
  72159. };
  72160. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  72161. //if no device orientation provided, don't update the rotation.
  72162. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  72163. if (!this._alpha)
  72164. return;
  72165. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  72166. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  72167. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  72168. //Mirror on XY Plane
  72169. this._camera.rotationQuaternion.z *= -1;
  72170. this._camera.rotationQuaternion.w *= -1;
  72171. };
  72172. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  72173. return "FreeCameraDeviceOrientationInput";
  72174. };
  72175. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  72176. return "deviceOrientation";
  72177. };
  72178. return FreeCameraDeviceOrientationInput;
  72179. }());
  72180. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  72181. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  72182. })(BABYLON || (BABYLON = {}));
  72183. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  72184. var BABYLON;
  72185. (function (BABYLON) {
  72186. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  72187. function ArcRotateCameraVRDeviceOrientationInput() {
  72188. this.alphaCorrection = 1;
  72189. this.betaCorrection = 1;
  72190. this.gammaCorrection = 1;
  72191. this._alpha = 0;
  72192. this._gamma = 0;
  72193. this._dirty = false;
  72194. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  72195. }
  72196. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  72197. this.camera.attachControl(element, noPreventDefault);
  72198. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  72199. };
  72200. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  72201. if (evt.alpha !== null) {
  72202. this._alpha = +evt.alpha | 0;
  72203. }
  72204. if (evt.gamma !== null) {
  72205. this._gamma = +evt.gamma | 0;
  72206. }
  72207. this._dirty = true;
  72208. };
  72209. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  72210. if (this._dirty) {
  72211. this._dirty = false;
  72212. if (this._gamma < 0) {
  72213. this._gamma = 180 + this._gamma;
  72214. }
  72215. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  72216. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  72217. }
  72218. };
  72219. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  72220. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  72221. };
  72222. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  72223. return "ArcRotateCameraVRDeviceOrientationInput";
  72224. };
  72225. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  72226. return "VRDeviceOrientation";
  72227. };
  72228. return ArcRotateCameraVRDeviceOrientationInput;
  72229. }());
  72230. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  72231. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  72232. })(BABYLON || (BABYLON = {}));
  72233. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  72234. var BABYLON;
  72235. (function (BABYLON) {
  72236. var VRCameraMetrics = /** @class */ (function () {
  72237. function VRCameraMetrics() {
  72238. this.compensateDistortion = true;
  72239. }
  72240. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  72241. get: function () {
  72242. return this.hResolution / (2 * this.vResolution);
  72243. },
  72244. enumerable: true,
  72245. configurable: true
  72246. });
  72247. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  72248. get: function () {
  72249. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  72250. },
  72251. enumerable: true,
  72252. configurable: true
  72253. });
  72254. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  72255. get: function () {
  72256. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  72257. var h = (4 * meters) / this.hScreenSize;
  72258. return BABYLON.Matrix.Translation(h, 0, 0);
  72259. },
  72260. enumerable: true,
  72261. configurable: true
  72262. });
  72263. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  72264. get: function () {
  72265. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  72266. var h = (4 * meters) / this.hScreenSize;
  72267. return BABYLON.Matrix.Translation(-h, 0, 0);
  72268. },
  72269. enumerable: true,
  72270. configurable: true
  72271. });
  72272. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  72273. get: function () {
  72274. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  72275. },
  72276. enumerable: true,
  72277. configurable: true
  72278. });
  72279. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  72280. get: function () {
  72281. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  72282. },
  72283. enumerable: true,
  72284. configurable: true
  72285. });
  72286. VRCameraMetrics.GetDefault = function () {
  72287. var result = new VRCameraMetrics();
  72288. result.hResolution = 1280;
  72289. result.vResolution = 800;
  72290. result.hScreenSize = 0.149759993;
  72291. result.vScreenSize = 0.0935999975;
  72292. result.vScreenCenter = 0.0467999987;
  72293. result.eyeToScreenDistance = 0.0410000011;
  72294. result.lensSeparationDistance = 0.0635000020;
  72295. result.interpupillaryDistance = 0.0640000030;
  72296. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  72297. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  72298. result.postProcessScaleFactor = 1.714605507808412;
  72299. result.lensCenterOffset = 0.151976421;
  72300. return result;
  72301. };
  72302. return VRCameraMetrics;
  72303. }());
  72304. BABYLON.VRCameraMetrics = VRCameraMetrics;
  72305. })(BABYLON || (BABYLON = {}));
  72306. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  72307. var BABYLON;
  72308. (function (BABYLON) {
  72309. var WebVRFreeCamera = /** @class */ (function (_super) {
  72310. __extends(WebVRFreeCamera, _super);
  72311. function WebVRFreeCamera(name, position, scene, webVROptions) {
  72312. if (webVROptions === void 0) { webVROptions = {}; }
  72313. var _this = _super.call(this, name, position, scene) || this;
  72314. _this.webVROptions = webVROptions;
  72315. _this._vrDevice = null;
  72316. _this.rawPose = null;
  72317. _this._specsVersion = "1.1";
  72318. _this._attached = false;
  72319. _this._descendants = [];
  72320. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  72321. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  72322. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  72323. _this._standingMatrix = null;
  72324. // Represents device position and rotation in babylon space
  72325. _this.devicePosition = BABYLON.Vector3.Zero();
  72326. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  72327. _this.deviceScaleFactor = 1;
  72328. _this._deviceToWorld = BABYLON.Matrix.Identity();
  72329. _this._worldToDevice = BABYLON.Matrix.Identity();
  72330. _this.controllers = [];
  72331. _this.onControllersAttachedObservable = new BABYLON.Observable();
  72332. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  72333. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  72334. _this._defaultHeight = 0;
  72335. _this.deviceDistanceToRoomGround = function () {
  72336. if (_this._standingMatrix) {
  72337. // Add standing matrix offset to get real offset from ground in room
  72338. _this._standingMatrix.getTranslationToRef(_this._workingVector);
  72339. return _this._deviceRoomPosition.y + _this._workingVector.y;
  72340. }
  72341. else {
  72342. return _this._defaultHeight;
  72343. }
  72344. };
  72345. _this.useStandingMatrix = function (callback) {
  72346. if (callback === void 0) { callback = function (bool) { }; }
  72347. // Use standing matrix if availible
  72348. if (!navigator || !navigator.getVRDisplays) {
  72349. callback(false);
  72350. }
  72351. else {
  72352. navigator.getVRDisplays().then(function (displays) {
  72353. if (!displays || !displays[0] || !displays[0].stageParameters || !displays[0].stageParameters.sittingToStandingTransform) {
  72354. callback(false);
  72355. }
  72356. else {
  72357. _this._standingMatrix = new BABYLON.Matrix();
  72358. BABYLON.Matrix.FromFloat32ArrayToRefScaled(displays[0].stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  72359. if (!_this.getScene().useRightHandedSystem) {
  72360. [2, 6, 8, 9, 14].forEach(function (num) {
  72361. if (_this._standingMatrix) {
  72362. _this._standingMatrix.m[num] *= -1;
  72363. }
  72364. });
  72365. }
  72366. callback(true);
  72367. }
  72368. });
  72369. }
  72370. };
  72371. _this._workingVector = BABYLON.Vector3.Zero();
  72372. _this._oneVector = BABYLON.Vector3.One();
  72373. _this._workingMatrix = BABYLON.Matrix.Identity();
  72374. _this._cache.position = BABYLON.Vector3.Zero();
  72375. if (webVROptions.defaultHeight) {
  72376. _this._defaultHeight = webVROptions.defaultHeight;
  72377. _this.position.y = _this._defaultHeight;
  72378. }
  72379. _this.minZ = 0.1;
  72380. //legacy support - the compensation boolean was removed.
  72381. if (arguments.length === 5) {
  72382. _this.webVROptions = arguments[4];
  72383. }
  72384. // default webVR options
  72385. if (_this.webVROptions.trackPosition == undefined) {
  72386. _this.webVROptions.trackPosition = true;
  72387. }
  72388. if (_this.webVROptions.controllerMeshes == undefined) {
  72389. _this.webVROptions.controllerMeshes = true;
  72390. }
  72391. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  72392. _this.webVROptions.defaultLightingOnControllers = true;
  72393. }
  72394. _this.rotationQuaternion = new BABYLON.Quaternion();
  72395. if (_this.webVROptions && _this.webVROptions.positionScale) {
  72396. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  72397. }
  72398. //enable VR
  72399. var engine = _this.getEngine();
  72400. _this._onVREnabled = function (success) { if (success) {
  72401. _this.initControllers();
  72402. } };
  72403. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  72404. engine.initWebVR().add(function (event) {
  72405. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  72406. return;
  72407. }
  72408. _this._vrDevice = event.vrDisplay;
  72409. //reset the rig parameters.
  72410. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  72411. if (_this._attached) {
  72412. _this.getEngine().enableVR();
  72413. }
  72414. });
  72415. if (typeof (VRFrameData) !== "undefined")
  72416. _this._frameData = new VRFrameData();
  72417. /**
  72418. * The idea behind the following lines:
  72419. * objects that have the camera as parent should actually have the rig cameras as a parent.
  72420. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  72421. * the second will not show it correctly.
  72422. *
  72423. * To solve this - each object that has the camera as parent will be added to a protected array.
  72424. * When the rig camera renders, it will take this array and set all of those to be its children.
  72425. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  72426. * Amazing!
  72427. */
  72428. scene.onBeforeCameraRenderObservable.add(function (camera) {
  72429. if (camera.parent === _this && _this.rigParenting) {
  72430. _this._descendants = _this.getDescendants(true, function (n) {
  72431. // don't take the cameras or the controllers!
  72432. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  72433. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  72434. return !isController && !isRigCamera;
  72435. });
  72436. _this._descendants.forEach(function (node) {
  72437. node.parent = camera;
  72438. });
  72439. }
  72440. });
  72441. scene.onAfterCameraRenderObservable.add(function (camera) {
  72442. if (camera.parent === _this && _this.rigParenting) {
  72443. _this._descendants.forEach(function (node) {
  72444. node.parent = _this;
  72445. });
  72446. }
  72447. });
  72448. return _this;
  72449. }
  72450. WebVRFreeCamera.prototype.dispose = function () {
  72451. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  72452. _super.prototype.dispose.call(this);
  72453. };
  72454. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  72455. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  72456. var gp = _a[_i];
  72457. if (gp.hand === name) {
  72458. return gp;
  72459. }
  72460. }
  72461. return null;
  72462. };
  72463. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  72464. get: function () {
  72465. if (!this._leftController) {
  72466. this._leftController = this.getControllerByName("left");
  72467. }
  72468. return this._leftController;
  72469. },
  72470. enumerable: true,
  72471. configurable: true
  72472. });
  72473. ;
  72474. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  72475. get: function () {
  72476. if (!this._rightController) {
  72477. this._rightController = this.getControllerByName("right");
  72478. }
  72479. return this._rightController;
  72480. },
  72481. enumerable: true,
  72482. configurable: true
  72483. });
  72484. ;
  72485. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  72486. if (length === void 0) { length = 100; }
  72487. if (this.leftCamera) {
  72488. // Use left eye to avoid computation to compute center on every call
  72489. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  72490. }
  72491. else {
  72492. return _super.prototype.getForwardRay.call(this, length);
  72493. }
  72494. };
  72495. WebVRFreeCamera.prototype._checkInputs = function () {
  72496. if (this._vrDevice && this._vrDevice.isPresenting) {
  72497. this._vrDevice.getFrameData(this._frameData);
  72498. this.updateFromDevice(this._frameData.pose);
  72499. }
  72500. _super.prototype._checkInputs.call(this);
  72501. };
  72502. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  72503. if (poseData && poseData.orientation) {
  72504. this.rawPose = poseData;
  72505. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  72506. if (this.getScene().useRightHandedSystem) {
  72507. this._deviceRoomRotationQuaternion.z *= -1;
  72508. this._deviceRoomRotationQuaternion.w *= -1;
  72509. }
  72510. if (this.webVROptions.trackPosition && this.rawPose.position) {
  72511. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  72512. if (this.getScene().useRightHandedSystem) {
  72513. this._deviceRoomPosition.z *= -1;
  72514. }
  72515. }
  72516. }
  72517. };
  72518. /**
  72519. * WebVR's attach control will start broadcasting frames to the device.
  72520. * Note that in certain browsers (chrome for example) this function must be called
  72521. * within a user-interaction callback. Example:
  72522. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  72523. *
  72524. * @param {HTMLElement} element
  72525. * @param {boolean} [noPreventDefault]
  72526. *
  72527. * @memberOf WebVRFreeCamera
  72528. */
  72529. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  72530. _super.prototype.attachControl.call(this, element, noPreventDefault);
  72531. this._attached = true;
  72532. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  72533. if (this._vrDevice) {
  72534. this.getEngine().enableVR();
  72535. }
  72536. };
  72537. WebVRFreeCamera.prototype.detachControl = function (element) {
  72538. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  72539. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  72540. _super.prototype.detachControl.call(this, element);
  72541. this._attached = false;
  72542. this.getEngine().disableVR();
  72543. };
  72544. WebVRFreeCamera.prototype.getClassName = function () {
  72545. return "WebVRFreeCamera";
  72546. };
  72547. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  72548. //uses the vrDisplay's "resetPose()".
  72549. //pitch and roll won't be affected.
  72550. this._vrDevice.resetPose();
  72551. };
  72552. WebVRFreeCamera.prototype._updateRigCameras = function () {
  72553. var camLeft = this._rigCameras[0];
  72554. var camRight = this._rigCameras[1];
  72555. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  72556. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  72557. camLeft.position.copyFrom(this._deviceRoomPosition);
  72558. camRight.position.copyFrom(this._deviceRoomPosition);
  72559. };
  72560. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  72561. var _this = this;
  72562. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  72563. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  72564. if (!this.updateCacheCalled) {
  72565. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  72566. this.updateCacheCalled = true;
  72567. this.update();
  72568. }
  72569. // Set working vector to the device position in room space rotated by the new rotation
  72570. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  72571. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  72572. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  72573. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  72574. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  72575. // Add translation from anchor position
  72576. this._deviceToWorld.getTranslationToRef(this._workingVector);
  72577. this._workingVector.addInPlace(this.position);
  72578. this._workingVector.subtractInPlace(this._cache.position);
  72579. this._deviceToWorld.setTranslation(this._workingVector);
  72580. // Set an inverted matrix to be used when updating the camera
  72581. this._deviceToWorld.invertToRef(this._worldToDevice);
  72582. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  72583. this.controllers.forEach(function (controller) {
  72584. controller._deviceToWorld = _this._deviceToWorld;
  72585. controller.update();
  72586. });
  72587. }
  72588. if (!ignoreParentClass) {
  72589. _super.prototype._updateCache.call(this);
  72590. }
  72591. this.updateCacheCalled = false;
  72592. };
  72593. WebVRFreeCamera.prototype.update = function () {
  72594. // Get current device position in babylon world
  72595. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  72596. // Get current device rotation in babylon world
  72597. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  72598. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  72599. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  72600. _super.prototype.update.call(this);
  72601. };
  72602. WebVRFreeCamera.prototype._getViewMatrix = function () {
  72603. return BABYLON.Matrix.Identity();
  72604. };
  72605. /**
  72606. * This function is called by the two RIG cameras.
  72607. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  72608. */
  72609. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  72610. var _this = this;
  72611. //WebVR 1.1
  72612. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  72613. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  72614. if (!this.getScene().useRightHandedSystem) {
  72615. [2, 6, 8, 9, 14].forEach(function (num) {
  72616. _this._webvrViewMatrix.m[num] *= -1;
  72617. });
  72618. }
  72619. // update the camera rotation matrix
  72620. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  72621. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  72622. // Computing target and final matrix
  72623. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  72624. var parentCamera = this._cameraRigParams["parentCamera"];
  72625. // should the view matrix be updated with scale and position offset?
  72626. if (parentCamera.deviceScaleFactor !== 1) {
  72627. this._webvrViewMatrix.invert();
  72628. // scale the position, if set
  72629. if (parentCamera.deviceScaleFactor) {
  72630. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  72631. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  72632. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  72633. }
  72634. this._webvrViewMatrix.invert();
  72635. }
  72636. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  72637. return this._webvrViewMatrix;
  72638. };
  72639. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  72640. var _this = this;
  72641. var parentCamera = this.parent;
  72642. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  72643. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  72644. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  72645. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  72646. //babylon compatible matrix
  72647. if (!this.getScene().useRightHandedSystem) {
  72648. [8, 9, 10, 11].forEach(function (num) {
  72649. _this._projectionMatrix.m[num] *= -1;
  72650. });
  72651. }
  72652. return this._projectionMatrix;
  72653. };
  72654. WebVRFreeCamera.prototype.initControllers = function () {
  72655. var _this = this;
  72656. this.controllers = [];
  72657. var manager = this.getScene().gamepadManager;
  72658. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  72659. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  72660. var webVrController = gamepad;
  72661. if (webVrController.defaultModel) {
  72662. webVrController.defaultModel.setEnabled(false);
  72663. }
  72664. if (webVrController.hand === "right") {
  72665. _this._rightController = null;
  72666. }
  72667. if (webVrController.hand === "left") {
  72668. _this._rightController = null;
  72669. }
  72670. var controllerIndex = _this.controllers.indexOf(webVrController);
  72671. if (controllerIndex !== -1) {
  72672. _this.controllers.splice(controllerIndex, 1);
  72673. }
  72674. }
  72675. });
  72676. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  72677. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  72678. var webVrController_1 = gamepad;
  72679. webVrController_1._deviceToWorld = _this._deviceToWorld;
  72680. if (_this.webVROptions.controllerMeshes) {
  72681. if (webVrController_1.defaultModel) {
  72682. webVrController_1.defaultModel.setEnabled(true);
  72683. }
  72684. else {
  72685. // Load the meshes
  72686. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  72687. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  72688. if (_this.webVROptions.defaultLightingOnControllers) {
  72689. if (!_this._lightOnControllers) {
  72690. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  72691. }
  72692. var activateLightOnSubMeshes_1 = function (mesh, light) {
  72693. var children = mesh.getChildren();
  72694. if (children.length !== 0) {
  72695. children.forEach(function (mesh) {
  72696. light.includedOnlyMeshes.push(mesh);
  72697. activateLightOnSubMeshes_1(mesh, light);
  72698. });
  72699. }
  72700. };
  72701. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  72702. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  72703. }
  72704. });
  72705. }
  72706. }
  72707. webVrController_1.attachToPoseControlledCamera(_this);
  72708. // since this is async - sanity check. Is the controller already stored?
  72709. if (_this.controllers.indexOf(webVrController_1) === -1) {
  72710. //add to the controllers array
  72711. _this.controllers.push(webVrController_1);
  72712. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  72713. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  72714. // So we're overriding setting left & right manually to be sure
  72715. var firstViveWandDetected = false;
  72716. for (var i = 0; i < _this.controllers.length; i++) {
  72717. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  72718. if (!firstViveWandDetected) {
  72719. firstViveWandDetected = true;
  72720. _this.controllers[i].hand = "left";
  72721. }
  72722. else {
  72723. _this.controllers[i].hand = "right";
  72724. }
  72725. }
  72726. }
  72727. //did we find enough controllers? Great! let the developer know.
  72728. if (_this.controllers.length >= 2) {
  72729. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  72730. }
  72731. }
  72732. }
  72733. });
  72734. };
  72735. return WebVRFreeCamera;
  72736. }(BABYLON.FreeCamera));
  72737. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  72738. })(BABYLON || (BABYLON = {}));
  72739. //# sourceMappingURL=babylon.webVRCamera.js.map
  72740. var BABYLON;
  72741. (function (BABYLON) {
  72742. // We're mainly based on the logic defined into the FreeCamera code
  72743. var DeviceOrientationCamera = /** @class */ (function (_super) {
  72744. __extends(DeviceOrientationCamera, _super);
  72745. function DeviceOrientationCamera(name, position, scene) {
  72746. var _this = _super.call(this, name, position, scene) || this;
  72747. _this._quaternionCache = new BABYLON.Quaternion();
  72748. _this.inputs.addDeviceOrientation();
  72749. return _this;
  72750. }
  72751. DeviceOrientationCamera.prototype.getClassName = function () {
  72752. return "DeviceOrientationCamera";
  72753. };
  72754. DeviceOrientationCamera.prototype._checkInputs = function () {
  72755. _super.prototype._checkInputs.call(this);
  72756. this._quaternionCache.copyFrom(this.rotationQuaternion);
  72757. if (this._initialQuaternion) {
  72758. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  72759. }
  72760. };
  72761. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  72762. var _this = this;
  72763. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  72764. //can only work if this camera has a rotation quaternion already.
  72765. if (!this.rotationQuaternion)
  72766. return;
  72767. if (!this._initialQuaternion) {
  72768. this._initialQuaternion = new BABYLON.Quaternion();
  72769. }
  72770. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  72771. ['x', 'y', 'z'].forEach(function (axisName) {
  72772. if (!axis[axisName]) {
  72773. _this._initialQuaternion[axisName] = 0;
  72774. }
  72775. else {
  72776. _this._initialQuaternion[axisName] *= -1;
  72777. }
  72778. });
  72779. this._initialQuaternion.normalize();
  72780. //force rotation update
  72781. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  72782. };
  72783. return DeviceOrientationCamera;
  72784. }(BABYLON.FreeCamera));
  72785. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  72786. })(BABYLON || (BABYLON = {}));
  72787. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  72788. var BABYLON;
  72789. (function (BABYLON) {
  72790. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  72791. __extends(VRDeviceOrientationFreeCamera, _super);
  72792. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  72793. if (compensateDistortion === void 0) { compensateDistortion = true; }
  72794. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  72795. var _this = _super.call(this, name, position, scene) || this;
  72796. vrCameraMetrics.compensateDistortion = compensateDistortion;
  72797. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  72798. return _this;
  72799. }
  72800. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  72801. return "VRDeviceOrientationFreeCamera";
  72802. };
  72803. return VRDeviceOrientationFreeCamera;
  72804. }(BABYLON.DeviceOrientationCamera));
  72805. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  72806. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  72807. __extends(VRDeviceOrientationGamepadCamera, _super);
  72808. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  72809. if (compensateDistortion === void 0) { compensateDistortion = true; }
  72810. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  72811. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  72812. _this.inputs.addGamepad();
  72813. return _this;
  72814. }
  72815. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  72816. return "VRDeviceOrientationGamepadCamera";
  72817. };
  72818. return VRDeviceOrientationGamepadCamera;
  72819. }(VRDeviceOrientationFreeCamera));
  72820. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  72821. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  72822. __extends(VRDeviceOrientationArcRotateCamera, _super);
  72823. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  72824. if (compensateDistortion === void 0) { compensateDistortion = true; }
  72825. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  72826. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  72827. vrCameraMetrics.compensateDistortion = compensateDistortion;
  72828. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  72829. _this.inputs.addVRDeviceOrientation();
  72830. return _this;
  72831. }
  72832. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  72833. return "VRDeviceOrientationArcRotateCamera";
  72834. };
  72835. return VRDeviceOrientationArcRotateCamera;
  72836. }(BABYLON.ArcRotateCamera));
  72837. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  72838. })(BABYLON || (BABYLON = {}));
  72839. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  72840. var BABYLON;
  72841. (function (BABYLON) {
  72842. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  72843. __extends(AnaglyphFreeCamera, _super);
  72844. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  72845. var _this = _super.call(this, name, position, scene) || this;
  72846. _this.interaxialDistance = interaxialDistance;
  72847. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  72848. return _this;
  72849. }
  72850. AnaglyphFreeCamera.prototype.getClassName = function () {
  72851. return "AnaglyphFreeCamera";
  72852. };
  72853. return AnaglyphFreeCamera;
  72854. }(BABYLON.FreeCamera));
  72855. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  72856. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  72857. __extends(AnaglyphArcRotateCamera, _super);
  72858. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  72859. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  72860. _this.interaxialDistance = interaxialDistance;
  72861. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  72862. return _this;
  72863. }
  72864. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  72865. return "AnaglyphArcRotateCamera";
  72866. };
  72867. return AnaglyphArcRotateCamera;
  72868. }(BABYLON.ArcRotateCamera));
  72869. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  72870. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  72871. __extends(AnaglyphGamepadCamera, _super);
  72872. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  72873. var _this = _super.call(this, name, position, scene) || this;
  72874. _this.interaxialDistance = interaxialDistance;
  72875. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  72876. return _this;
  72877. }
  72878. AnaglyphGamepadCamera.prototype.getClassName = function () {
  72879. return "AnaglyphGamepadCamera";
  72880. };
  72881. return AnaglyphGamepadCamera;
  72882. }(BABYLON.GamepadCamera));
  72883. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  72884. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  72885. __extends(AnaglyphUniversalCamera, _super);
  72886. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  72887. var _this = _super.call(this, name, position, scene) || this;
  72888. _this.interaxialDistance = interaxialDistance;
  72889. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  72890. return _this;
  72891. }
  72892. AnaglyphUniversalCamera.prototype.getClassName = function () {
  72893. return "AnaglyphUniversalCamera";
  72894. };
  72895. return AnaglyphUniversalCamera;
  72896. }(BABYLON.UniversalCamera));
  72897. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  72898. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  72899. __extends(StereoscopicFreeCamera, _super);
  72900. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  72901. var _this = _super.call(this, name, position, scene) || this;
  72902. _this.interaxialDistance = interaxialDistance;
  72903. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  72904. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  72905. return _this;
  72906. }
  72907. StereoscopicFreeCamera.prototype.getClassName = function () {
  72908. return "StereoscopicFreeCamera";
  72909. };
  72910. return StereoscopicFreeCamera;
  72911. }(BABYLON.FreeCamera));
  72912. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  72913. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  72914. __extends(StereoscopicArcRotateCamera, _super);
  72915. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  72916. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  72917. _this.interaxialDistance = interaxialDistance;
  72918. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  72919. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  72920. return _this;
  72921. }
  72922. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  72923. return "StereoscopicArcRotateCamera";
  72924. };
  72925. return StereoscopicArcRotateCamera;
  72926. }(BABYLON.ArcRotateCamera));
  72927. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  72928. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  72929. __extends(StereoscopicGamepadCamera, _super);
  72930. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  72931. var _this = _super.call(this, name, position, scene) || this;
  72932. _this.interaxialDistance = interaxialDistance;
  72933. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  72934. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  72935. return _this;
  72936. }
  72937. StereoscopicGamepadCamera.prototype.getClassName = function () {
  72938. return "StereoscopicGamepadCamera";
  72939. };
  72940. return StereoscopicGamepadCamera;
  72941. }(BABYLON.GamepadCamera));
  72942. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  72943. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  72944. __extends(StereoscopicUniversalCamera, _super);
  72945. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  72946. var _this = _super.call(this, name, position, scene) || this;
  72947. _this.interaxialDistance = interaxialDistance;
  72948. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  72949. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  72950. return _this;
  72951. }
  72952. StereoscopicUniversalCamera.prototype.getClassName = function () {
  72953. return "StereoscopicUniversalCamera";
  72954. };
  72955. return StereoscopicUniversalCamera;
  72956. }(BABYLON.UniversalCamera));
  72957. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  72958. })(BABYLON || (BABYLON = {}));
  72959. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  72960. var BABYLON;
  72961. (function (BABYLON) {
  72962. var VRExperienceHelper = /** @class */ (function () {
  72963. function VRExperienceHelper(scene, webVROptions) {
  72964. if (webVROptions === void 0) { webVROptions = {}; }
  72965. var _this = this;
  72966. this.webVROptions = webVROptions;
  72967. // Can the system support WebVR, even if a headset isn't plugged in?
  72968. this._webVRsupported = false;
  72969. // If WebVR is supported, is a headset plugged in and are we ready to present?
  72970. this._webVRready = false;
  72971. // Are we waiting for the requestPresent callback to complete?
  72972. this._webVRrequesting = false;
  72973. // Are we presenting to the headset right now?
  72974. this._webVRpresenting = false;
  72975. // Are we presenting in the fullscreen fallback?
  72976. this._fullscreenVRpresenting = false;
  72977. /**
  72978. * Observable raised when entering VR.
  72979. */
  72980. this.onEnteringVRObservable = new BABYLON.Observable();
  72981. /**
  72982. * Observable raised when exiting VR.
  72983. */
  72984. this.onExitingVRObservable = new BABYLON.Observable();
  72985. /**
  72986. * Observable raised when controller mesh is loaded.
  72987. */
  72988. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  72989. this._useCustomVRButton = false;
  72990. this._teleportationRequested = false;
  72991. this._teleportationEnabledOnLeftController = false;
  72992. this._teleportationEnabledOnRightController = false;
  72993. this._interactionsEnabledOnLeftController = false;
  72994. this._interactionsEnabledOnRightController = false;
  72995. this._leftControllerReady = false;
  72996. this._rightControllerReady = false;
  72997. this._floorMeshesCollection = [];
  72998. this._teleportationAllowed = false;
  72999. this._rotationAllowed = true;
  73000. this._teleportationRequestInitiated = false;
  73001. this._teleportationBackRequestInitiated = false;
  73002. this.teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  73003. this._rotationRightAsked = false;
  73004. this._rotationLeftAsked = false;
  73005. this._isDefaultTeleportationTarget = true;
  73006. this._teleportationFillColor = "#444444";
  73007. this._teleportationBorderColor = "#FFFFFF";
  73008. this._rotationAngle = 0;
  73009. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  73010. this._padSensibilityUp = 0.65;
  73011. this._padSensibilityDown = 0.35;
  73012. this.onNewMeshSelected = new BABYLON.Observable();
  73013. /**
  73014. * Observable raised before camera teleportation
  73015. */
  73016. this.onBeforeCameraTeleport = new BABYLON.Observable();
  73017. /**
  73018. * Observable raised after camera teleportation
  73019. */
  73020. this.onAfterCameraTeleport = new BABYLON.Observable();
  73021. /**
  73022. * Observable raised when current selected mesh gets unselected
  73023. */
  73024. this.onSelectedMeshUnselected = new BABYLON.Observable();
  73025. this._pointerDownOnMeshAsked = false;
  73026. this._isActionableMesh = false;
  73027. this._teleportationEnabled = false;
  73028. this._interactionsEnabled = false;
  73029. this._interactionsRequested = false;
  73030. this._displayGaze = true;
  73031. this._displayLaserPointer = true;
  73032. this._dpadPressed = true;
  73033. this._onResize = function () {
  73034. _this.moveButtonToBottomRight();
  73035. if (_this._fullscreenVRpresenting && _this._webVRready) {
  73036. _this.exitVR();
  73037. }
  73038. };
  73039. this._onFullscreenChange = function () {
  73040. if (document.fullscreen !== undefined) {
  73041. _this._fullscreenVRpresenting = document.fullscreen;
  73042. }
  73043. else if (document.mozFullScreen !== undefined) {
  73044. _this._fullscreenVRpresenting = document.mozFullScreen;
  73045. }
  73046. else if (document.webkitIsFullScreen !== undefined) {
  73047. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  73048. }
  73049. else if (document.msIsFullScreen !== undefined) {
  73050. _this._fullscreenVRpresenting = document.msIsFullScreen;
  73051. }
  73052. if (!_this._fullscreenVRpresenting && _this._canvas) {
  73053. _this.exitVR();
  73054. if (!_this._useCustomVRButton) {
  73055. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  73056. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  73057. }
  73058. }
  73059. };
  73060. this.beforeRender = function () {
  73061. _this._castRayAndSelectObject();
  73062. };
  73063. this._onNewGamepadConnected = function (gamepad) {
  73064. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  73065. if (gamepad.leftStick) {
  73066. gamepad.onleftstickchanged(function (stickValues) {
  73067. if (_this._teleportationEnabled) {
  73068. // Listening to classic/xbox gamepad only if no VR controller is active
  73069. if ((!_this._leftLaserPointer && !_this._rightLaserPointer) ||
  73070. ((_this._leftLaserPointer && !_this._leftLaserPointer.isVisible) &&
  73071. (_this._rightLaserPointer && !_this._rightLaserPointer.isVisible))) {
  73072. _this._checkTeleportWithRay(stickValues);
  73073. _this._checkTeleportBackwards(stickValues);
  73074. }
  73075. }
  73076. });
  73077. }
  73078. if (gamepad.rightStick) {
  73079. gamepad.onrightstickchanged(function (stickValues) {
  73080. if (_this._teleportationEnabled) {
  73081. _this._checkRotate(stickValues);
  73082. }
  73083. });
  73084. }
  73085. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  73086. gamepad.onbuttondown(function (buttonPressed) {
  73087. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  73088. _this._selectionPointerDown();
  73089. }
  73090. });
  73091. gamepad.onbuttonup(function (buttonPressed) {
  73092. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  73093. _this._selectionPointerUp();
  73094. }
  73095. });
  73096. }
  73097. }
  73098. else {
  73099. var webVRController = gamepad;
  73100. _this._tryEnableInteractionOnController(webVRController);
  73101. }
  73102. };
  73103. // 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
  73104. this._tryEnableInteractionOnController = function (webVRController) {
  73105. if (webVRController.hand === "left") {
  73106. _this._leftControllerReady = true;
  73107. if (_this._interactionsRequested && !_this._interactionsEnabledOnLeftController) {
  73108. _this._enableInteractionOnController(webVRController);
  73109. }
  73110. if (_this._teleportationRequested && !_this._teleportationEnabledOnLeftController) {
  73111. _this._enableTeleportationOnController(webVRController);
  73112. }
  73113. }
  73114. if (webVRController.hand === "right") {
  73115. _this._rightControllerReady = true;
  73116. if (_this._interactionsRequested && !_this._interactionsEnabledOnRightController) {
  73117. _this._enableInteractionOnController(webVRController);
  73118. }
  73119. if (_this._teleportationRequested && !_this._teleportationEnabledOnRightController) {
  73120. _this._enableTeleportationOnController(webVRController);
  73121. }
  73122. }
  73123. };
  73124. this._onNewGamepadDisconnected = function (gamepad) {
  73125. if (gamepad instanceof BABYLON.WebVRController) {
  73126. if (gamepad.hand === "left") {
  73127. _this._interactionsEnabledOnLeftController = false;
  73128. _this._teleportationEnabledOnLeftController = false;
  73129. _this._leftControllerReady = false;
  73130. if (_this._leftLaserPointer) {
  73131. _this._leftLaserPointer.dispose();
  73132. }
  73133. }
  73134. if (gamepad.hand === "right") {
  73135. _this._interactionsEnabledOnRightController = false;
  73136. _this._teleportationEnabledOnRightController = false;
  73137. _this._rightControllerReady = false;
  73138. if (_this._rightLaserPointer) {
  73139. _this._rightLaserPointer.dispose();
  73140. }
  73141. }
  73142. }
  73143. };
  73144. this._workingVector = BABYLON.Vector3.Zero();
  73145. this._workingQuaternion = BABYLON.Quaternion.Identity();
  73146. this._workingMatrix = BABYLON.Matrix.Identity();
  73147. this._scene = scene;
  73148. this._canvas = scene.getEngine().getRenderingCanvas();
  73149. // Parse options
  73150. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  73151. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  73152. }
  73153. if (webVROptions.createDeviceOrientationCamera === undefined) {
  73154. webVROptions.createDeviceOrientationCamera = true;
  73155. }
  73156. if (webVROptions.defaultHeight === undefined) {
  73157. webVROptions.defaultHeight = 1.7;
  73158. }
  73159. if (webVROptions.useCustomVRButton) {
  73160. this._useCustomVRButton = true;
  73161. if (webVROptions.customVRButton) {
  73162. this._btnVR = webVROptions.customVRButton;
  73163. }
  73164. }
  73165. if (webVROptions.rayLength) {
  73166. this._rayLength = webVROptions.rayLength;
  73167. }
  73168. this._defaultHeight = webVROptions.defaultHeight;
  73169. // Set position
  73170. if (this._scene.activeCamera) {
  73171. this._position = this._scene.activeCamera.position.clone();
  73172. }
  73173. else {
  73174. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  73175. }
  73176. // Set non-vr camera
  73177. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  73178. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  73179. // Copy data from existing camera
  73180. if (this._scene.activeCamera) {
  73181. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  73182. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  73183. // Set rotation from previous camera
  73184. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  73185. var targetCamera = this._scene.activeCamera;
  73186. if (targetCamera.rotationQuaternion) {
  73187. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  73188. }
  73189. else {
  73190. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  73191. }
  73192. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  73193. }
  73194. }
  73195. this._scene.activeCamera = this._deviceOrientationCamera;
  73196. if (this._canvas) {
  73197. this._scene.activeCamera.attachControl(this._canvas);
  73198. }
  73199. }
  73200. else {
  73201. this._existingCamera = this._scene.activeCamera;
  73202. }
  73203. // Create VR cameras
  73204. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  73205. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  73206. }
  73207. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  73208. this._webVRCamera.useStandingMatrix();
  73209. // Create default button
  73210. if (!this._useCustomVRButton) {
  73211. this._btnVR = document.createElement("BUTTON");
  73212. this._btnVR.className = "babylonVRicon";
  73213. this._btnVR.id = "babylonVRiconbtn";
  73214. this._btnVR.title = "Click to switch to VR";
  73215. 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) }";
  73216. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  73217. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  73218. // css += ".babylonVRicon.vrdisplaysupported { }";
  73219. // css += ".babylonVRicon.vrdisplayready { }";
  73220. // css += ".babylonVRicon.vrdisplayrequesting { }";
  73221. var style = document.createElement('style');
  73222. style.appendChild(document.createTextNode(css));
  73223. document.getElementsByTagName('head')[0].appendChild(style);
  73224. this.moveButtonToBottomRight();
  73225. }
  73226. // VR button click event
  73227. if (this._btnVR) {
  73228. this._btnVR.addEventListener("click", function () {
  73229. if (!_this.isInVRMode) {
  73230. _this.enterVR();
  73231. }
  73232. else {
  73233. _this.exitVR();
  73234. }
  73235. });
  73236. }
  73237. // Window events
  73238. window.addEventListener("resize", this._onResize);
  73239. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  73240. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  73241. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  73242. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  73243. // Display vr button when headset is connected
  73244. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  73245. this.displayVRButton();
  73246. }
  73247. else {
  73248. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  73249. if (e.vrDisplay) {
  73250. _this.displayVRButton();
  73251. }
  73252. });
  73253. }
  73254. // Exiting VR mode using 'ESC' key on desktop
  73255. this._onKeyDown = function (event) {
  73256. if (event.keyCode === 27 && _this.isInVRMode) {
  73257. _this.exitVR();
  73258. }
  73259. };
  73260. document.addEventListener("keydown", this._onKeyDown);
  73261. // Exiting VR mode double tapping the touch screen
  73262. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  73263. if (_this.isInVRMode) {
  73264. _this.exitVR();
  73265. if (_this._fullscreenVRpresenting) {
  73266. _this._scene.getEngine().switchFullscreen(true);
  73267. }
  73268. }
  73269. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  73270. // Listen for WebVR display changes
  73271. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  73272. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  73273. this._onVRRequestPresentStart = function () {
  73274. _this._webVRrequesting = true;
  73275. _this.updateButtonVisibility();
  73276. };
  73277. this._onVRRequestPresentComplete = function (success) {
  73278. _this._webVRrequesting = false;
  73279. _this.updateButtonVisibility();
  73280. };
  73281. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  73282. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  73283. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  73284. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  73285. scene.onDisposeObservable.add(function () {
  73286. _this.dispose();
  73287. });
  73288. // Gamepad connection events
  73289. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  73290. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  73291. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  73292. this.updateButtonVisibility();
  73293. //create easing functions
  73294. this._circleEase = new BABYLON.CircleEase();
  73295. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  73296. }
  73297. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  73298. /** Return this.onEnteringVRObservable
  73299. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  73300. */
  73301. get: function () {
  73302. return this.onEnteringVRObservable;
  73303. },
  73304. enumerable: true,
  73305. configurable: true
  73306. });
  73307. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  73308. /** Return this.onExitingVRObservable
  73309. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  73310. */
  73311. get: function () {
  73312. return this.onExitingVRObservable;
  73313. },
  73314. enumerable: true,
  73315. configurable: true
  73316. });
  73317. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  73318. /** Return this.onControllerMeshLoadedObservable
  73319. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  73320. */
  73321. get: function () {
  73322. return this.onControllerMeshLoadedObservable;
  73323. },
  73324. enumerable: true,
  73325. configurable: true
  73326. });
  73327. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  73328. get: function () {
  73329. return this._teleportationTarget;
  73330. },
  73331. set: function (value) {
  73332. if (value) {
  73333. value.name = "teleportationTarget";
  73334. this._isDefaultTeleportationTarget = false;
  73335. this._teleportationTarget = value;
  73336. }
  73337. },
  73338. enumerable: true,
  73339. configurable: true
  73340. });
  73341. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  73342. get: function () {
  73343. return this._displayGaze;
  73344. },
  73345. set: function (value) {
  73346. this._displayGaze = value;
  73347. if (!value) {
  73348. this._gazeTracker.isVisible = false;
  73349. }
  73350. },
  73351. enumerable: true,
  73352. configurable: true
  73353. });
  73354. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  73355. get: function () {
  73356. return this._displayLaserPointer;
  73357. },
  73358. set: function (value) {
  73359. this._displayLaserPointer = value;
  73360. if (!value) {
  73361. if (this._rightLaserPointer) {
  73362. this._rightLaserPointer.isVisible = false;
  73363. }
  73364. if (this._leftLaserPointer) {
  73365. this._leftLaserPointer.isVisible = false;
  73366. }
  73367. }
  73368. else {
  73369. if (this._rightLaserPointer) {
  73370. this._rightLaserPointer.isVisible = true;
  73371. }
  73372. else if (this._leftLaserPointer) {
  73373. this._leftLaserPointer.isVisible = true;
  73374. }
  73375. }
  73376. },
  73377. enumerable: true,
  73378. configurable: true
  73379. });
  73380. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  73381. get: function () {
  73382. return this._deviceOrientationCamera;
  73383. },
  73384. enumerable: true,
  73385. configurable: true
  73386. });
  73387. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  73388. // Based on the current WebVR support, returns the current VR camera used
  73389. get: function () {
  73390. if (this._webVRready) {
  73391. return this._webVRCamera;
  73392. }
  73393. else {
  73394. return this._scene.activeCamera;
  73395. }
  73396. },
  73397. enumerable: true,
  73398. configurable: true
  73399. });
  73400. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  73401. get: function () {
  73402. return this._webVRCamera;
  73403. },
  73404. enumerable: true,
  73405. configurable: true
  73406. });
  73407. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  73408. get: function () {
  73409. return this._vrDeviceOrientationCamera;
  73410. },
  73411. enumerable: true,
  73412. configurable: true
  73413. });
  73414. // Raised when one of the controller has loaded successfully its associated default mesh
  73415. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  73416. this._tryEnableInteractionOnController(webVRController);
  73417. try {
  73418. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  73419. }
  73420. catch (err) {
  73421. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  73422. }
  73423. };
  73424. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  73425. /**
  73426. * Gets a value indicating if we are currently in VR mode.
  73427. */
  73428. get: function () {
  73429. return this._webVRpresenting || this._fullscreenVRpresenting;
  73430. },
  73431. enumerable: true,
  73432. configurable: true
  73433. });
  73434. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  73435. var vrDisplay = this._scene.getEngine().getVRDevice();
  73436. if (vrDisplay) {
  73437. var wasPresenting = this._webVRpresenting;
  73438. // A VR display is connected
  73439. this._webVRpresenting = vrDisplay.isPresenting;
  73440. if (wasPresenting && !this._webVRpresenting)
  73441. this.exitVR();
  73442. }
  73443. else {
  73444. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  73445. }
  73446. this.updateButtonVisibility();
  73447. };
  73448. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  73449. this._webVRsupported = eventArgs.vrSupported;
  73450. this._webVRready = !!eventArgs.vrDisplay;
  73451. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  73452. this.updateButtonVisibility();
  73453. };
  73454. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  73455. if (this._canvas && !this._useCustomVRButton) {
  73456. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  73457. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  73458. }
  73459. };
  73460. VRExperienceHelper.prototype.displayVRButton = function () {
  73461. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  73462. document.body.appendChild(this._btnVR);
  73463. this._btnVRDisplayed = true;
  73464. }
  73465. };
  73466. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  73467. if (!this._btnVR || this._useCustomVRButton) {
  73468. return;
  73469. }
  73470. this._btnVR.className = "babylonVRicon";
  73471. if (this.isInVRMode) {
  73472. this._btnVR.className += " vrdisplaypresenting";
  73473. }
  73474. else {
  73475. if (this._webVRready)
  73476. this._btnVR.className += " vrdisplayready";
  73477. if (this._webVRsupported)
  73478. this._btnVR.className += " vrdisplaysupported";
  73479. if (this._webVRrequesting)
  73480. this._btnVR.className += " vrdisplayrequesting";
  73481. }
  73482. };
  73483. /**
  73484. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  73485. * Otherwise, will use the fullscreen API.
  73486. */
  73487. VRExperienceHelper.prototype.enterVR = function () {
  73488. if (this.onEnteringVRObservable) {
  73489. try {
  73490. this.onEnteringVRObservable.notifyObservers(this);
  73491. }
  73492. catch (err) {
  73493. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  73494. }
  73495. }
  73496. if (this._scene.activeCamera) {
  73497. this._position = this._scene.activeCamera.position.clone();
  73498. // make sure that we return to the last active camera
  73499. this._existingCamera = this._scene.activeCamera;
  73500. }
  73501. if (this._webVRrequesting)
  73502. return;
  73503. // If WebVR is supported and a headset is connected
  73504. if (this._webVRready) {
  73505. if (!this._webVRpresenting) {
  73506. this._webVRCamera.position = this._position;
  73507. this._scene.activeCamera = this._webVRCamera;
  73508. }
  73509. }
  73510. else if (this._vrDeviceOrientationCamera) {
  73511. this._vrDeviceOrientationCamera.position = this._position;
  73512. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  73513. this._scene.getEngine().switchFullscreen(true);
  73514. this.updateButtonVisibility();
  73515. }
  73516. if (this._scene.activeCamera && this._canvas) {
  73517. this._scene.activeCamera.attachControl(this._canvas);
  73518. }
  73519. if (this._interactionsEnabled) {
  73520. this._scene.registerBeforeRender(this.beforeRender);
  73521. }
  73522. };
  73523. /**
  73524. * Attempt to exit VR, or fullscreen.
  73525. */
  73526. VRExperienceHelper.prototype.exitVR = function () {
  73527. if (this.onExitingVRObservable) {
  73528. try {
  73529. this.onExitingVRObservable.notifyObservers(this);
  73530. }
  73531. catch (err) {
  73532. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  73533. }
  73534. }
  73535. if (this._webVRpresenting) {
  73536. this._scene.getEngine().disableVR();
  73537. }
  73538. if (this._scene.activeCamera) {
  73539. this._position = this._scene.activeCamera.position.clone();
  73540. }
  73541. if (this._deviceOrientationCamera) {
  73542. this._deviceOrientationCamera.position = this._position;
  73543. this._scene.activeCamera = this._deviceOrientationCamera;
  73544. if (this._canvas) {
  73545. this._scene.activeCamera.attachControl(this._canvas);
  73546. }
  73547. }
  73548. else if (this._existingCamera) {
  73549. this._existingCamera.position = this._position;
  73550. this._scene.activeCamera = this._existingCamera;
  73551. }
  73552. this.updateButtonVisibility();
  73553. if (this._interactionsEnabled) {
  73554. this._scene.unregisterBeforeRender(this.beforeRender);
  73555. }
  73556. };
  73557. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  73558. get: function () {
  73559. return this._position;
  73560. },
  73561. set: function (value) {
  73562. this._position = value;
  73563. if (this._scene.activeCamera) {
  73564. this._scene.activeCamera.position = value;
  73565. }
  73566. },
  73567. enumerable: true,
  73568. configurable: true
  73569. });
  73570. VRExperienceHelper.prototype.enableInteractions = function () {
  73571. var _this = this;
  73572. if (!this._interactionsEnabled) {
  73573. this._interactionsRequested = true;
  73574. if (this._leftControllerReady && this._webVRCamera.leftController) {
  73575. this._enableInteractionOnController(this._webVRCamera.leftController);
  73576. }
  73577. if (this._rightControllerReady && this._webVRCamera.rightController) {
  73578. this._enableInteractionOnController(this._webVRCamera.rightController);
  73579. }
  73580. this._createGazeTracker();
  73581. this.raySelectionPredicate = function (mesh) {
  73582. return true;
  73583. };
  73584. this.meshSelectionPredicate = function (mesh) {
  73585. return true;
  73586. };
  73587. this._raySelectionPredicate = function (mesh) {
  73588. if (_this._isTeleportationFloor(mesh) || (mesh.isVisible && mesh.name.indexOf("gazeTracker") === -1
  73589. && mesh.name.indexOf("teleportationTarget") === -1
  73590. && mesh.name.indexOf("torusTeleportation") === -1
  73591. && mesh.name.indexOf("laserPointer") === -1)) {
  73592. return _this.raySelectionPredicate(mesh);
  73593. }
  73594. return false;
  73595. };
  73596. this._interactionsEnabled = true;
  73597. }
  73598. };
  73599. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  73600. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  73601. if (this._floorMeshesCollection[i].id === mesh.id) {
  73602. return true;
  73603. }
  73604. }
  73605. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  73606. return true;
  73607. }
  73608. return false;
  73609. };
  73610. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  73611. if (!this._floorMeshesCollection) {
  73612. return;
  73613. }
  73614. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  73615. return;
  73616. }
  73617. this._floorMeshesCollection.push(floorMesh);
  73618. };
  73619. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  73620. if (!this._floorMeshesCollection) {
  73621. return;
  73622. }
  73623. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  73624. if (meshIndex !== -1) {
  73625. this._floorMeshesCollection.splice(meshIndex, 1);
  73626. }
  73627. };
  73628. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  73629. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  73630. if (!this._teleportationEnabled) {
  73631. this._teleportationRequested = true;
  73632. this.enableInteractions();
  73633. if (vrTeleportationOptions.floorMeshName) {
  73634. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  73635. }
  73636. if (vrTeleportationOptions.floorMeshes) {
  73637. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  73638. }
  73639. if (this._leftControllerReady && this._webVRCamera.leftController) {
  73640. this._enableTeleportationOnController(this._webVRCamera.leftController);
  73641. }
  73642. if (this._rightControllerReady && this._webVRCamera.rightController) {
  73643. this._enableTeleportationOnController(this._webVRCamera.rightController);
  73644. }
  73645. // Creates an image processing post process for the vignette not relying
  73646. // on the main scene configuration for image processing to reduce setup and spaces
  73647. // (gamma/linear) conflicts.
  73648. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  73649. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  73650. imageProcessingConfiguration.vignetteEnabled = true;
  73651. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  73652. this._webVRCamera.detachPostProcess(this._postProcessMove);
  73653. this._passProcessMove = new BABYLON.PassPostProcess("pass", 1.0, this._webVRCamera);
  73654. this._teleportationEnabled = true;
  73655. if (this._isDefaultTeleportationTarget) {
  73656. this._createTeleportationCircles();
  73657. }
  73658. }
  73659. };
  73660. VRExperienceHelper.prototype._enableInteractionOnController = function (webVRController) {
  73661. var _this = this;
  73662. var controllerMesh = webVRController.mesh;
  73663. if (controllerMesh) {
  73664. var makeNotPick = function (root) {
  73665. root.name += " laserPointer";
  73666. root.getChildMeshes().forEach(function (c) {
  73667. makeNotPick(c);
  73668. });
  73669. };
  73670. makeNotPick(controllerMesh);
  73671. var childMeshes = controllerMesh.getChildMeshes();
  73672. for (var i = 0; i < childMeshes.length; i++) {
  73673. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  73674. controllerMesh = childMeshes[i];
  73675. break;
  73676. }
  73677. }
  73678. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, this._scene, false);
  73679. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  73680. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  73681. laserPointerMaterial.alpha = 0.6;
  73682. laserPointer.material = laserPointerMaterial;
  73683. laserPointer.rotation.x = Math.PI / 2;
  73684. laserPointer.parent = controllerMesh;
  73685. laserPointer.position.z = -0.5;
  73686. laserPointer.isVisible = false;
  73687. if (webVRController.hand === "left") {
  73688. this._leftLaserPointer = laserPointer;
  73689. this._interactionsEnabledOnLeftController = true;
  73690. if (!this._rightLaserPointer) {
  73691. this._leftLaserPointer.isVisible = true;
  73692. }
  73693. }
  73694. else {
  73695. this._rightLaserPointer = laserPointer;
  73696. this._interactionsEnabledOnRightController = true;
  73697. if (!this._leftLaserPointer) {
  73698. this._rightLaserPointer.isVisible = true;
  73699. }
  73700. }
  73701. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  73702. // Enabling / disabling laserPointer
  73703. if (_this._displayLaserPointer && stateObject.value === 1) {
  73704. laserPointer.isVisible = !laserPointer.isVisible;
  73705. // Laser pointer can only be active on left or right, not both at the same time
  73706. if (webVRController.hand === "left" && _this._rightLaserPointer) {
  73707. _this._rightLaserPointer.isVisible = false;
  73708. }
  73709. else if (_this._leftLaserPointer) {
  73710. _this._leftLaserPointer.isVisible = false;
  73711. }
  73712. }
  73713. });
  73714. webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  73715. if (!_this._pointerDownOnMeshAsked) {
  73716. if (stateObject.value > _this._padSensibilityUp) {
  73717. _this._selectionPointerDown();
  73718. }
  73719. }
  73720. else if (stateObject.value < _this._padSensibilityDown) {
  73721. _this._selectionPointerUp();
  73722. }
  73723. });
  73724. }
  73725. };
  73726. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, webVRController) {
  73727. if (webVRController === void 0) { webVRController = null; }
  73728. if (!this._teleportationRequestInitiated) {
  73729. if (stateObject.y < -this._padSensibilityUp && this._dpadPressed) {
  73730. if (webVRController) {
  73731. // If laser pointer wasn't enabled yet
  73732. if (this._displayLaserPointer && webVRController.hand === "left" && this._leftLaserPointer) {
  73733. this._leftLaserPointer.isVisible = true;
  73734. if (this._rightLaserPointer) {
  73735. this._rightLaserPointer.isVisible = false;
  73736. }
  73737. }
  73738. else if (this._displayLaserPointer && this._rightLaserPointer) {
  73739. this._rightLaserPointer.isVisible = true;
  73740. if (this._leftLaserPointer) {
  73741. this._leftLaserPointer.isVisible = false;
  73742. }
  73743. }
  73744. }
  73745. this._teleportationRequestInitiated = true;
  73746. }
  73747. }
  73748. else {
  73749. // Listening to the proper controller values changes to confirm teleportation
  73750. if (webVRController == null
  73751. || (webVRController.hand === "left" && this._leftLaserPointer && this._leftLaserPointer.isVisible)
  73752. || (webVRController.hand === "right" && this._rightLaserPointer && this._rightLaserPointer.isVisible)) {
  73753. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  73754. if (this._teleportationAllowed) {
  73755. this._teleportationAllowed = false;
  73756. this._teleportCamera();
  73757. }
  73758. this._teleportationRequestInitiated = false;
  73759. }
  73760. }
  73761. }
  73762. };
  73763. VRExperienceHelper.prototype._selectionPointerDown = function () {
  73764. this._pointerDownOnMeshAsked = true;
  73765. if (this._currentMeshSelected && this._currentHit) {
  73766. this._scene.simulatePointerDown(this._currentHit);
  73767. }
  73768. };
  73769. VRExperienceHelper.prototype._selectionPointerUp = function () {
  73770. if (this._currentMeshSelected && this._currentHit) {
  73771. this._scene.simulatePointerUp(this._currentHit);
  73772. }
  73773. this._pointerDownOnMeshAsked = false;
  73774. };
  73775. VRExperienceHelper.prototype._checkRotate = function (stateObject) {
  73776. // Only rotate when user is not currently selecting a teleportation location
  73777. if (this._teleportationRequestInitiated) {
  73778. return;
  73779. }
  73780. if (!this._rotationLeftAsked) {
  73781. if (stateObject.x < -this._padSensibilityUp && this._dpadPressed) {
  73782. this._rotationLeftAsked = true;
  73783. if (this._rotationAllowed) {
  73784. this._rotateCamera(false);
  73785. }
  73786. }
  73787. }
  73788. else {
  73789. if (stateObject.x > -this._padSensibilityDown) {
  73790. this._rotationLeftAsked = false;
  73791. }
  73792. }
  73793. if (!this._rotationRightAsked) {
  73794. if (stateObject.x > this._padSensibilityUp && this._dpadPressed) {
  73795. this._rotationRightAsked = true;
  73796. if (this._rotationAllowed) {
  73797. this._rotateCamera(true);
  73798. }
  73799. }
  73800. }
  73801. else {
  73802. if (stateObject.x < this._padSensibilityDown) {
  73803. this._rotationRightAsked = false;
  73804. }
  73805. }
  73806. };
  73807. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject) {
  73808. // Only teleport backwards when user is not currently selecting a teleportation location
  73809. if (this._teleportationRequestInitiated) {
  73810. return;
  73811. }
  73812. // Teleport backwards
  73813. if (stateObject.y > this._padSensibilityUp && this._dpadPressed) {
  73814. if (!this._teleportationBackRequestInitiated) {
  73815. if (!this.currentVRCamera) {
  73816. return;
  73817. }
  73818. // Get rotation and position of the current camera
  73819. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  73820. var position = this.currentVRCamera.position;
  73821. // If the camera has device position, use that instead
  73822. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  73823. rotation = this.currentVRCamera.deviceRotationQuaternion;
  73824. position = this.currentVRCamera.devicePosition;
  73825. }
  73826. // Get matrix with only the y rotation of the device rotation
  73827. rotation.toEulerAnglesToRef(this._workingVector);
  73828. this._workingVector.z = 0;
  73829. this._workingVector.x = 0;
  73830. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  73831. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  73832. // Rotate backwards ray by device rotation to cast at the ground behind the user
  73833. BABYLON.Vector3.TransformCoordinatesToRef(this.teleportBackwardsVector, this._workingMatrix, this._workingVector);
  73834. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  73835. var ray = new BABYLON.Ray(position, this._workingVector);
  73836. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  73837. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  73838. this._teleportCamera(hit.pickedPoint);
  73839. }
  73840. this._teleportationBackRequestInitiated = true;
  73841. }
  73842. }
  73843. else {
  73844. this._teleportationBackRequestInitiated = false;
  73845. }
  73846. };
  73847. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  73848. var _this = this;
  73849. var controllerMesh = webVRController.mesh;
  73850. if (controllerMesh) {
  73851. if (webVRController.hand === "left") {
  73852. if (!this._interactionsEnabledOnLeftController) {
  73853. this._enableInteractionOnController(webVRController);
  73854. }
  73855. this._teleportationEnabledOnLeftController = true;
  73856. }
  73857. else {
  73858. if (!this._interactionsEnabledOnRightController) {
  73859. this._enableInteractionOnController(webVRController);
  73860. }
  73861. this._teleportationEnabledOnRightController = true;
  73862. }
  73863. if (webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  73864. this._dpadPressed = false;
  73865. webVRController.onPadStateChangedObservable.add(function (stateObject) {
  73866. _this._dpadPressed = stateObject.pressed;
  73867. if (!_this._dpadPressed) {
  73868. _this._rotationLeftAsked = false;
  73869. _this._rotationRightAsked = false;
  73870. _this._teleportationBackRequestInitiated = false;
  73871. }
  73872. });
  73873. }
  73874. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  73875. _this._checkTeleportBackwards(stateObject);
  73876. _this._checkTeleportWithRay(stateObject, webVRController);
  73877. _this._checkRotate(stateObject);
  73878. });
  73879. }
  73880. };
  73881. // Gaze support used to point to teleport or to interact with an object
  73882. VRExperienceHelper.prototype._createGazeTracker = function () {
  73883. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, this._scene, false);
  73884. this._gazeTracker.bakeCurrentTransformIntoVertices();
  73885. this._gazeTracker.isPickable = false;
  73886. this._gazeTracker.isVisible = false;
  73887. var targetMat = new BABYLON.StandardMaterial("targetMat", this._scene);
  73888. targetMat.specularColor = BABYLON.Color3.Black();
  73889. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  73890. targetMat.backFaceCulling = false;
  73891. this._gazeTracker.material = targetMat;
  73892. };
  73893. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  73894. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  73895. this._teleportationTarget.isPickable = false;
  73896. var length = 512;
  73897. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  73898. dynamicTexture.hasAlpha = true;
  73899. var context = dynamicTexture.getContext();
  73900. var centerX = length / 2;
  73901. var centerY = length / 2;
  73902. var radius = 200;
  73903. context.beginPath();
  73904. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  73905. context.fillStyle = this._teleportationFillColor;
  73906. context.fill();
  73907. context.lineWidth = 10;
  73908. context.strokeStyle = this._teleportationBorderColor;
  73909. context.stroke();
  73910. context.closePath();
  73911. dynamicTexture.update();
  73912. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  73913. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  73914. this._teleportationTarget.material = teleportationCircleMaterial;
  73915. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  73916. torus.isPickable = false;
  73917. torus.parent = this._teleportationTarget;
  73918. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  73919. var keys = [];
  73920. keys.push({
  73921. frame: 0,
  73922. value: 0
  73923. });
  73924. keys.push({
  73925. frame: 30,
  73926. value: 0.4
  73927. });
  73928. keys.push({
  73929. frame: 60,
  73930. value: 0
  73931. });
  73932. animationInnerCircle.setKeys(keys);
  73933. var easingFunction = new BABYLON.SineEase();
  73934. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  73935. animationInnerCircle.setEasingFunction(easingFunction);
  73936. torus.animations = [];
  73937. torus.animations.push(animationInnerCircle);
  73938. this._scene.beginAnimation(torus, 0, 60, true);
  73939. this._hideTeleportationTarget();
  73940. };
  73941. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  73942. if (this._teleportationEnabled) {
  73943. this._teleportationTarget.isVisible = true;
  73944. if (this._isDefaultTeleportationTarget) {
  73945. this._teleportationTarget.getChildren()[0].isVisible = true;
  73946. }
  73947. }
  73948. };
  73949. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  73950. if (this._teleportationEnabled) {
  73951. this._teleportationTarget.isVisible = false;
  73952. if (this._isDefaultTeleportationTarget) {
  73953. this._teleportationTarget.getChildren()[0].isVisible = false;
  73954. }
  73955. }
  73956. };
  73957. VRExperienceHelper.prototype._rotateCamera = function (right) {
  73958. var _this = this;
  73959. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  73960. return;
  73961. }
  73962. if (right) {
  73963. this._rotationAngle++;
  73964. }
  73965. else {
  73966. this._rotationAngle--;
  73967. }
  73968. this.currentVRCamera.animations = [];
  73969. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  73970. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  73971. var animationRotationKeys = [];
  73972. animationRotationKeys.push({
  73973. frame: 0,
  73974. value: this.currentVRCamera.rotationQuaternion
  73975. });
  73976. animationRotationKeys.push({
  73977. frame: 6,
  73978. value: target
  73979. });
  73980. animationRotation.setKeys(animationRotationKeys);
  73981. animationRotation.setEasingFunction(this._circleEase);
  73982. this.currentVRCamera.animations.push(animationRotation);
  73983. this._postProcessMove.animations = [];
  73984. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  73985. var vignetteWeightKeys = [];
  73986. vignetteWeightKeys.push({
  73987. frame: 0,
  73988. value: 0
  73989. });
  73990. vignetteWeightKeys.push({
  73991. frame: 3,
  73992. value: 4
  73993. });
  73994. vignetteWeightKeys.push({
  73995. frame: 6,
  73996. value: 0
  73997. });
  73998. animationPP.setKeys(vignetteWeightKeys);
  73999. animationPP.setEasingFunction(this._circleEase);
  74000. this._postProcessMove.animations.push(animationPP);
  74001. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74002. var vignetteStretchKeys = [];
  74003. vignetteStretchKeys.push({
  74004. frame: 0,
  74005. value: 0
  74006. });
  74007. vignetteStretchKeys.push({
  74008. frame: 3,
  74009. value: 10
  74010. });
  74011. vignetteStretchKeys.push({
  74012. frame: 6,
  74013. value: 0
  74014. });
  74015. animationPP2.setKeys(vignetteStretchKeys);
  74016. animationPP2.setEasingFunction(this._circleEase);
  74017. this._postProcessMove.animations.push(animationPP2);
  74018. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  74019. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  74020. this._webVRCamera.attachPostProcess(this._postProcessMove);
  74021. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  74022. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  74023. });
  74024. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  74025. };
  74026. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit) {
  74027. if (hit.pickedPoint) {
  74028. this._teleportationAllowed = true;
  74029. if (this._teleportationRequestInitiated) {
  74030. this._displayTeleportationTarget();
  74031. }
  74032. else {
  74033. this._hideTeleportationTarget();
  74034. }
  74035. this._haloCenter.copyFrom(hit.pickedPoint);
  74036. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  74037. var pickNormal = hit.getNormal(true, false);
  74038. if (pickNormal) {
  74039. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  74040. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  74041. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  74042. }
  74043. this._teleportationTarget.position.y += 0.1;
  74044. }
  74045. };
  74046. VRExperienceHelper.prototype._teleportCamera = function (location) {
  74047. var _this = this;
  74048. if (location === void 0) { location = null; }
  74049. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  74050. return;
  74051. }
  74052. if (!location) {
  74053. location = this._haloCenter;
  74054. }
  74055. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  74056. // offset of the headset from the anchor.
  74057. if (this.webVRCamera.leftCamera) {
  74058. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  74059. this._workingVector.subtractInPlace(this.webVRCamera.position);
  74060. location.subtractToRef(this._workingVector, this._workingVector);
  74061. }
  74062. else {
  74063. this._workingVector.copyFrom(location);
  74064. }
  74065. // Add height to account for user's height offset
  74066. if (this.isInVRMode) {
  74067. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  74068. }
  74069. else {
  74070. this._workingVector.y += this._defaultHeight;
  74071. }
  74072. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  74073. // Create animation from the camera's position to the new location
  74074. this.currentVRCamera.animations = [];
  74075. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74076. var animationCameraTeleportationKeys = [{
  74077. frame: 0,
  74078. value: this.currentVRCamera.position
  74079. },
  74080. {
  74081. frame: 11,
  74082. value: this._workingVector
  74083. }
  74084. ];
  74085. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  74086. animationCameraTeleportation.setEasingFunction(this._circleEase);
  74087. this.currentVRCamera.animations.push(animationCameraTeleportation);
  74088. this._postProcessMove.animations = [];
  74089. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74090. var vignetteWeightKeys = [];
  74091. vignetteWeightKeys.push({
  74092. frame: 0,
  74093. value: 0
  74094. });
  74095. vignetteWeightKeys.push({
  74096. frame: 5,
  74097. value: 8
  74098. });
  74099. vignetteWeightKeys.push({
  74100. frame: 11,
  74101. value: 0
  74102. });
  74103. animationPP.setKeys(vignetteWeightKeys);
  74104. this._postProcessMove.animations.push(animationPP);
  74105. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74106. var vignetteStretchKeys = [];
  74107. vignetteStretchKeys.push({
  74108. frame: 0,
  74109. value: 0
  74110. });
  74111. vignetteStretchKeys.push({
  74112. frame: 5,
  74113. value: 10
  74114. });
  74115. vignetteStretchKeys.push({
  74116. frame: 11,
  74117. value: 0
  74118. });
  74119. animationPP2.setKeys(vignetteStretchKeys);
  74120. this._postProcessMove.animations.push(animationPP2);
  74121. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  74122. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  74123. this._webVRCamera.attachPostProcess(this._postProcessMove);
  74124. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  74125. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  74126. });
  74127. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  74128. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  74129. });
  74130. };
  74131. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  74132. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  74133. return;
  74134. }
  74135. var ray;
  74136. if (this._leftLaserPointer && this._leftLaserPointer.isVisible && this.currentVRCamera.leftController) {
  74137. ray = this.currentVRCamera.leftController.getForwardRay(this._rayLength);
  74138. }
  74139. else if (this._rightLaserPointer && this._rightLaserPointer.isVisible && this.currentVRCamera.rightController) {
  74140. ray = this.currentVRCamera.rightController.getForwardRay(this._rayLength);
  74141. }
  74142. else {
  74143. ray = this.currentVRCamera.getForwardRay(this._rayLength);
  74144. }
  74145. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  74146. // Moving the gazeTracker on the mesh face targetted
  74147. if (hit && hit.pickedPoint) {
  74148. if (this._displayGaze) {
  74149. var multiplier = 1;
  74150. this._gazeTracker.isVisible = true;
  74151. if (this._isActionableMesh) {
  74152. multiplier = 3;
  74153. }
  74154. this._gazeTracker.scaling.x = hit.distance * multiplier;
  74155. this._gazeTracker.scaling.y = hit.distance * multiplier;
  74156. this._gazeTracker.scaling.z = hit.distance * multiplier;
  74157. var pickNormal = hit.getNormal();
  74158. // To avoid z-fighting
  74159. var deltaFighting = 0.002;
  74160. if (pickNormal) {
  74161. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  74162. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  74163. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._gazeTracker.rotation);
  74164. }
  74165. this._gazeTracker.position.copyFrom(hit.pickedPoint);
  74166. if (this._gazeTracker.position.x < 0) {
  74167. this._gazeTracker.position.x += deltaFighting;
  74168. }
  74169. else {
  74170. this._gazeTracker.position.x -= deltaFighting;
  74171. }
  74172. if (this._gazeTracker.position.y < 0) {
  74173. this._gazeTracker.position.y += deltaFighting;
  74174. }
  74175. else {
  74176. this._gazeTracker.position.y -= deltaFighting;
  74177. }
  74178. if (this._gazeTracker.position.z < 0) {
  74179. this._gazeTracker.position.z += deltaFighting;
  74180. }
  74181. else {
  74182. this._gazeTracker.position.z -= deltaFighting;
  74183. }
  74184. }
  74185. // Changing the size of the laser pointer based on the distance from the targetted point
  74186. if (this._rightLaserPointer && this._rightLaserPointer.isVisible) {
  74187. this._rightLaserPointer.scaling.y = hit.distance;
  74188. this._rightLaserPointer.position.z = -hit.distance / 2;
  74189. }
  74190. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  74191. this._leftLaserPointer.scaling.y = hit.distance;
  74192. this._leftLaserPointer.position.z = -hit.distance / 2;
  74193. }
  74194. }
  74195. else {
  74196. this._gazeTracker.isVisible = false;
  74197. }
  74198. if (hit && hit.pickedMesh) {
  74199. this._currentHit = hit;
  74200. if (this._pointerDownOnMeshAsked) {
  74201. this._scene.simulatePointerMove(this._currentHit);
  74202. }
  74203. // The object selected is the floor, we're in a teleportation scenario
  74204. if (this._teleportationEnabled && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  74205. // Moving the teleportation area to this targetted point
  74206. this._moveTeleportationSelectorTo(hit);
  74207. return;
  74208. }
  74209. // If not, we're in a selection scenario
  74210. this._hideTeleportationTarget();
  74211. this._teleportationAllowed = false;
  74212. if (hit.pickedMesh !== this._currentMeshSelected) {
  74213. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  74214. this._currentMeshSelected = hit.pickedMesh;
  74215. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  74216. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  74217. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  74218. this._isActionableMesh = true;
  74219. }
  74220. else {
  74221. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74222. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74223. this._isActionableMesh = false;
  74224. }
  74225. try {
  74226. this.onNewMeshSelected.notifyObservers(this._currentMeshSelected);
  74227. }
  74228. catch (err) {
  74229. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  74230. }
  74231. }
  74232. else {
  74233. if (this._currentMeshSelected) {
  74234. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  74235. }
  74236. this._currentMeshSelected = null;
  74237. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74238. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74239. }
  74240. }
  74241. }
  74242. else {
  74243. this._currentHit = null;
  74244. this._currentMeshSelected = null;
  74245. this._teleportationAllowed = false;
  74246. this._hideTeleportationTarget();
  74247. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74248. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74249. }
  74250. };
  74251. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  74252. if (this._leftLaserPointer && this._leftLaserPointer.material) {
  74253. this._leftLaserPointer.material.emissiveColor = color;
  74254. }
  74255. if (this._rightLaserPointer && this._rightLaserPointer.material) {
  74256. this._rightLaserPointer.material.emissiveColor = color;
  74257. }
  74258. };
  74259. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  74260. if (this._gazeTracker.material) {
  74261. this._gazeTracker.material.emissiveColor = color;
  74262. }
  74263. };
  74264. VRExperienceHelper.prototype.dispose = function () {
  74265. if (this.isInVRMode) {
  74266. this.exitVR();
  74267. }
  74268. if (this._passProcessMove) {
  74269. this._passProcessMove.dispose();
  74270. }
  74271. if (this._postProcessMove) {
  74272. this._postProcessMove.dispose();
  74273. }
  74274. if (this._webVRCamera) {
  74275. this._webVRCamera.dispose();
  74276. }
  74277. if (this._vrDeviceOrientationCamera) {
  74278. this._vrDeviceOrientationCamera.dispose();
  74279. }
  74280. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  74281. document.body.removeChild(this._btnVR);
  74282. }
  74283. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  74284. this._deviceOrientationCamera.dispose();
  74285. }
  74286. if (this._gazeTracker) {
  74287. this._gazeTracker.dispose();
  74288. }
  74289. if (this._teleportationTarget) {
  74290. this._teleportationTarget.dispose();
  74291. }
  74292. this._floorMeshesCollection = [];
  74293. document.removeEventListener("keydown", this._onKeyDown);
  74294. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  74295. window.removeEventListener("resize", this._onResize);
  74296. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  74297. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  74298. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  74299. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  74300. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  74301. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  74302. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  74303. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  74304. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  74305. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  74306. this._scene.unregisterBeforeRender(this.beforeRender);
  74307. };
  74308. VRExperienceHelper.prototype.getClassName = function () {
  74309. return "VRExperienceHelper";
  74310. };
  74311. return VRExperienceHelper;
  74312. }());
  74313. BABYLON.VRExperienceHelper = VRExperienceHelper;
  74314. })(BABYLON || (BABYLON = {}));
  74315. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  74316. // Mainly based on these 2 articles :
  74317. // 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
  74318. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  74319. var BABYLON;
  74320. (function (BABYLON) {
  74321. var JoystickAxis;
  74322. (function (JoystickAxis) {
  74323. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  74324. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  74325. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  74326. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  74327. var VirtualJoystick = /** @class */ (function () {
  74328. function VirtualJoystick(leftJoystick) {
  74329. var _this = this;
  74330. if (leftJoystick) {
  74331. this._leftJoystick = true;
  74332. }
  74333. else {
  74334. this._leftJoystick = false;
  74335. }
  74336. VirtualJoystick._globalJoystickIndex++;
  74337. // By default left & right arrow keys are moving the X
  74338. // and up & down keys are moving the Y
  74339. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  74340. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  74341. this.reverseLeftRight = false;
  74342. this.reverseUpDown = false;
  74343. // collections of pointers
  74344. this._touches = new BABYLON.StringDictionary();
  74345. this.deltaPosition = BABYLON.Vector3.Zero();
  74346. this._joystickSensibility = 25;
  74347. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  74348. this._onResize = function (evt) {
  74349. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  74350. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  74351. if (VirtualJoystick.vjCanvas) {
  74352. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  74353. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  74354. }
  74355. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  74356. };
  74357. // injecting a canvas element on top of the canvas 3D game
  74358. if (!VirtualJoystick.vjCanvas) {
  74359. window.addEventListener("resize", this._onResize, false);
  74360. VirtualJoystick.vjCanvas = document.createElement("canvas");
  74361. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  74362. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  74363. VirtualJoystick.vjCanvas.width = window.innerWidth;
  74364. VirtualJoystick.vjCanvas.height = window.innerHeight;
  74365. VirtualJoystick.vjCanvas.style.width = "100%";
  74366. VirtualJoystick.vjCanvas.style.height = "100%";
  74367. VirtualJoystick.vjCanvas.style.position = "absolute";
  74368. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  74369. VirtualJoystick.vjCanvas.style.top = "0px";
  74370. VirtualJoystick.vjCanvas.style.left = "0px";
  74371. VirtualJoystick.vjCanvas.style.zIndex = "5";
  74372. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  74373. // Support for jQuery PEP polyfill
  74374. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  74375. var context = VirtualJoystick.vjCanvas.getContext('2d');
  74376. if (!context) {
  74377. throw new Error("Unable to create canvas for virtual joystick");
  74378. }
  74379. VirtualJoystick.vjCanvasContext = context;
  74380. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  74381. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  74382. document.body.appendChild(VirtualJoystick.vjCanvas);
  74383. }
  74384. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  74385. this.pressed = false;
  74386. // default joystick color
  74387. this._joystickColor = "cyan";
  74388. this._joystickPointerID = -1;
  74389. // current joystick position
  74390. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  74391. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  74392. // origin joystick position
  74393. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  74394. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  74395. this._onPointerDownHandlerRef = function (evt) {
  74396. _this._onPointerDown(evt);
  74397. };
  74398. this._onPointerMoveHandlerRef = function (evt) {
  74399. _this._onPointerMove(evt);
  74400. };
  74401. this._onPointerUpHandlerRef = function (evt) {
  74402. _this._onPointerUp(evt);
  74403. };
  74404. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  74405. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  74406. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  74407. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  74408. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  74409. evt.preventDefault(); // Disables system menu
  74410. }, false);
  74411. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  74412. }
  74413. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  74414. this._joystickSensibility = newJoystickSensibility;
  74415. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  74416. };
  74417. VirtualJoystick.prototype._onPointerDown = function (e) {
  74418. var positionOnScreenCondition;
  74419. e.preventDefault();
  74420. if (this._leftJoystick === true) {
  74421. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  74422. }
  74423. else {
  74424. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  74425. }
  74426. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  74427. // First contact will be dedicated to the virtual joystick
  74428. this._joystickPointerID = e.pointerId;
  74429. this._joystickPointerStartPos.x = e.clientX;
  74430. this._joystickPointerStartPos.y = e.clientY;
  74431. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  74432. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  74433. this._deltaJoystickVector.x = 0;
  74434. this._deltaJoystickVector.y = 0;
  74435. this.pressed = true;
  74436. this._touches.add(e.pointerId.toString(), e);
  74437. }
  74438. else {
  74439. // You can only trigger the action buttons with a joystick declared
  74440. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  74441. this._action();
  74442. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  74443. }
  74444. }
  74445. };
  74446. VirtualJoystick.prototype._onPointerMove = function (e) {
  74447. // If the current pointer is the one associated to the joystick (first touch contact)
  74448. if (this._joystickPointerID == e.pointerId) {
  74449. this._joystickPointerPos.x = e.clientX;
  74450. this._joystickPointerPos.y = e.clientY;
  74451. this._deltaJoystickVector = this._joystickPointerPos.clone();
  74452. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  74453. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  74454. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  74455. switch (this._axisTargetedByLeftAndRight) {
  74456. case JoystickAxis.X:
  74457. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  74458. break;
  74459. case JoystickAxis.Y:
  74460. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  74461. break;
  74462. case JoystickAxis.Z:
  74463. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  74464. break;
  74465. }
  74466. var directionUpDown = this.reverseUpDown ? 1 : -1;
  74467. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  74468. switch (this._axisTargetedByUpAndDown) {
  74469. case JoystickAxis.X:
  74470. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  74471. break;
  74472. case JoystickAxis.Y:
  74473. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  74474. break;
  74475. case JoystickAxis.Z:
  74476. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  74477. break;
  74478. }
  74479. }
  74480. else {
  74481. var data = this._touches.get(e.pointerId.toString());
  74482. if (data) {
  74483. data.x = e.clientX;
  74484. data.y = e.clientY;
  74485. }
  74486. }
  74487. };
  74488. VirtualJoystick.prototype._onPointerUp = function (e) {
  74489. if (this._joystickPointerID == e.pointerId) {
  74490. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  74491. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  74492. this._joystickPointerID = -1;
  74493. this.pressed = false;
  74494. }
  74495. else {
  74496. var touch = this._touches.get(e.pointerId.toString());
  74497. if (touch) {
  74498. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  74499. }
  74500. }
  74501. this._deltaJoystickVector.x = 0;
  74502. this._deltaJoystickVector.y = 0;
  74503. this._touches.remove(e.pointerId.toString());
  74504. };
  74505. /**
  74506. * Change the color of the virtual joystick
  74507. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  74508. */
  74509. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  74510. this._joystickColor = newColor;
  74511. };
  74512. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  74513. this._action = action;
  74514. };
  74515. // Define which axis you'd like to control for left & right
  74516. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  74517. switch (axis) {
  74518. case JoystickAxis.X:
  74519. case JoystickAxis.Y:
  74520. case JoystickAxis.Z:
  74521. this._axisTargetedByLeftAndRight = axis;
  74522. break;
  74523. default:
  74524. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  74525. break;
  74526. }
  74527. };
  74528. // Define which axis you'd like to control for up & down
  74529. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  74530. switch (axis) {
  74531. case JoystickAxis.X:
  74532. case JoystickAxis.Y:
  74533. case JoystickAxis.Z:
  74534. this._axisTargetedByUpAndDown = axis;
  74535. break;
  74536. default:
  74537. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  74538. break;
  74539. }
  74540. };
  74541. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  74542. var _this = this;
  74543. if (this.pressed) {
  74544. this._touches.forEach(function (key, touch) {
  74545. if (touch.pointerId === _this._joystickPointerID) {
  74546. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  74547. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  74548. VirtualJoystick.vjCanvasContext.beginPath();
  74549. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  74550. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  74551. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  74552. VirtualJoystick.vjCanvasContext.stroke();
  74553. VirtualJoystick.vjCanvasContext.closePath();
  74554. VirtualJoystick.vjCanvasContext.beginPath();
  74555. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  74556. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  74557. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  74558. VirtualJoystick.vjCanvasContext.stroke();
  74559. VirtualJoystick.vjCanvasContext.closePath();
  74560. VirtualJoystick.vjCanvasContext.beginPath();
  74561. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  74562. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  74563. VirtualJoystick.vjCanvasContext.stroke();
  74564. VirtualJoystick.vjCanvasContext.closePath();
  74565. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  74566. }
  74567. else {
  74568. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  74569. VirtualJoystick.vjCanvasContext.beginPath();
  74570. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  74571. VirtualJoystick.vjCanvasContext.beginPath();
  74572. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  74573. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  74574. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  74575. VirtualJoystick.vjCanvasContext.stroke();
  74576. VirtualJoystick.vjCanvasContext.closePath();
  74577. touch.prevX = touch.x;
  74578. touch.prevY = touch.y;
  74579. }
  74580. ;
  74581. });
  74582. }
  74583. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  74584. };
  74585. VirtualJoystick.prototype.releaseCanvas = function () {
  74586. if (VirtualJoystick.vjCanvas) {
  74587. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  74588. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  74589. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  74590. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  74591. window.removeEventListener("resize", this._onResize);
  74592. document.body.removeChild(VirtualJoystick.vjCanvas);
  74593. VirtualJoystick.vjCanvas = null;
  74594. }
  74595. };
  74596. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  74597. VirtualJoystick._globalJoystickIndex = 0;
  74598. return VirtualJoystick;
  74599. }());
  74600. BABYLON.VirtualJoystick = VirtualJoystick;
  74601. })(BABYLON || (BABYLON = {}));
  74602. //# sourceMappingURL=babylon.virtualJoystick.js.map
  74603. var BABYLON;
  74604. (function (BABYLON) {
  74605. // We're mainly based on the logic defined into the FreeCamera code
  74606. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  74607. __extends(VirtualJoysticksCamera, _super);
  74608. function VirtualJoysticksCamera(name, position, scene) {
  74609. var _this = _super.call(this, name, position, scene) || this;
  74610. _this.inputs.addVirtualJoystick();
  74611. return _this;
  74612. }
  74613. VirtualJoysticksCamera.prototype.getClassName = function () {
  74614. return "VirtualJoysticksCamera";
  74615. };
  74616. return VirtualJoysticksCamera;
  74617. }(BABYLON.FreeCamera));
  74618. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  74619. })(BABYLON || (BABYLON = {}));
  74620. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  74621. var BABYLON;
  74622. (function (BABYLON) {
  74623. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  74624. function FreeCameraVirtualJoystickInput() {
  74625. }
  74626. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  74627. return this._leftjoystick;
  74628. };
  74629. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  74630. return this._rightjoystick;
  74631. };
  74632. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  74633. if (this._leftjoystick) {
  74634. var camera = this.camera;
  74635. var speed = camera._computeLocalCameraSpeed() * 50;
  74636. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  74637. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  74638. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  74639. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  74640. if (!this._leftjoystick.pressed) {
  74641. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  74642. }
  74643. if (!this._rightjoystick.pressed) {
  74644. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  74645. }
  74646. }
  74647. };
  74648. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  74649. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  74650. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  74651. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  74652. this._leftjoystick.setJoystickSensibility(0.15);
  74653. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  74654. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  74655. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  74656. this._rightjoystick.reverseUpDown = true;
  74657. this._rightjoystick.setJoystickSensibility(0.05);
  74658. this._rightjoystick.setJoystickColor("yellow");
  74659. };
  74660. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  74661. this._leftjoystick.releaseCanvas();
  74662. this._rightjoystick.releaseCanvas();
  74663. };
  74664. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  74665. return "FreeCameraVirtualJoystickInput";
  74666. };
  74667. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  74668. return "virtualJoystick";
  74669. };
  74670. return FreeCameraVirtualJoystickInput;
  74671. }());
  74672. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  74673. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  74674. })(BABYLON || (BABYLON = {}));
  74675. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  74676. var BABYLON;
  74677. (function (BABYLON) {
  74678. var SimplificationSettings = /** @class */ (function () {
  74679. function SimplificationSettings(quality, distance, optimizeMesh) {
  74680. this.quality = quality;
  74681. this.distance = distance;
  74682. this.optimizeMesh = optimizeMesh;
  74683. }
  74684. return SimplificationSettings;
  74685. }());
  74686. BABYLON.SimplificationSettings = SimplificationSettings;
  74687. var SimplificationQueue = /** @class */ (function () {
  74688. function SimplificationQueue() {
  74689. this.running = false;
  74690. this._simplificationArray = [];
  74691. }
  74692. SimplificationQueue.prototype.addTask = function (task) {
  74693. this._simplificationArray.push(task);
  74694. };
  74695. SimplificationQueue.prototype.executeNext = function () {
  74696. var task = this._simplificationArray.pop();
  74697. if (task) {
  74698. this.running = true;
  74699. this.runSimplification(task);
  74700. }
  74701. else {
  74702. this.running = false;
  74703. }
  74704. };
  74705. SimplificationQueue.prototype.runSimplification = function (task) {
  74706. var _this = this;
  74707. if (task.parallelProcessing) {
  74708. //parallel simplifier
  74709. task.settings.forEach(function (setting) {
  74710. var simplifier = _this.getSimplifier(task);
  74711. simplifier.simplify(setting, function (newMesh) {
  74712. task.mesh.addLODLevel(setting.distance, newMesh);
  74713. newMesh.isVisible = true;
  74714. //check if it is the last
  74715. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  74716. //all done, run the success callback.
  74717. task.successCallback();
  74718. }
  74719. _this.executeNext();
  74720. });
  74721. });
  74722. }
  74723. else {
  74724. //single simplifier.
  74725. var simplifier = this.getSimplifier(task);
  74726. var runDecimation = function (setting, callback) {
  74727. simplifier.simplify(setting, function (newMesh) {
  74728. task.mesh.addLODLevel(setting.distance, newMesh);
  74729. newMesh.isVisible = true;
  74730. //run the next quality level
  74731. callback();
  74732. });
  74733. };
  74734. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  74735. runDecimation(task.settings[loop.index], function () {
  74736. loop.executeNext();
  74737. });
  74738. }, function () {
  74739. //execution ended, run the success callback.
  74740. if (task.successCallback) {
  74741. task.successCallback();
  74742. }
  74743. _this.executeNext();
  74744. });
  74745. }
  74746. };
  74747. SimplificationQueue.prototype.getSimplifier = function (task) {
  74748. switch (task.simplificationType) {
  74749. case SimplificationType.QUADRATIC:
  74750. default:
  74751. return new QuadraticErrorSimplification(task.mesh);
  74752. }
  74753. };
  74754. return SimplificationQueue;
  74755. }());
  74756. BABYLON.SimplificationQueue = SimplificationQueue;
  74757. /**
  74758. * The implemented types of simplification.
  74759. * At the moment only Quadratic Error Decimation is implemented.
  74760. */
  74761. var SimplificationType;
  74762. (function (SimplificationType) {
  74763. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  74764. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  74765. var DecimationTriangle = /** @class */ (function () {
  74766. function DecimationTriangle(vertices) {
  74767. this.vertices = vertices;
  74768. this.error = new Array(4);
  74769. this.deleted = false;
  74770. this.isDirty = false;
  74771. this.deletePending = false;
  74772. this.borderFactor = 0;
  74773. }
  74774. return DecimationTriangle;
  74775. }());
  74776. BABYLON.DecimationTriangle = DecimationTriangle;
  74777. var DecimationVertex = /** @class */ (function () {
  74778. function DecimationVertex(position, id) {
  74779. this.position = position;
  74780. this.id = id;
  74781. this.isBorder = true;
  74782. this.q = new QuadraticMatrix();
  74783. this.triangleCount = 0;
  74784. this.triangleStart = 0;
  74785. this.originalOffsets = [];
  74786. }
  74787. DecimationVertex.prototype.updatePosition = function (newPosition) {
  74788. this.position.copyFrom(newPosition);
  74789. };
  74790. return DecimationVertex;
  74791. }());
  74792. BABYLON.DecimationVertex = DecimationVertex;
  74793. var QuadraticMatrix = /** @class */ (function () {
  74794. function QuadraticMatrix(data) {
  74795. this.data = new Array(10);
  74796. for (var i = 0; i < 10; ++i) {
  74797. if (data && data[i]) {
  74798. this.data[i] = data[i];
  74799. }
  74800. else {
  74801. this.data[i] = 0;
  74802. }
  74803. }
  74804. }
  74805. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  74806. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  74807. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  74808. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  74809. return det;
  74810. };
  74811. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  74812. for (var i = 0; i < 10; ++i) {
  74813. this.data[i] += matrix.data[i];
  74814. }
  74815. };
  74816. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  74817. for (var i = 0; i < 10; ++i) {
  74818. this.data[i] += data[i];
  74819. }
  74820. };
  74821. QuadraticMatrix.prototype.add = function (matrix) {
  74822. var m = new QuadraticMatrix();
  74823. for (var i = 0; i < 10; ++i) {
  74824. m.data[i] = this.data[i] + matrix.data[i];
  74825. }
  74826. return m;
  74827. };
  74828. QuadraticMatrix.FromData = function (a, b, c, d) {
  74829. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  74830. };
  74831. //returning an array to avoid garbage collection
  74832. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  74833. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  74834. };
  74835. return QuadraticMatrix;
  74836. }());
  74837. BABYLON.QuadraticMatrix = QuadraticMatrix;
  74838. var Reference = /** @class */ (function () {
  74839. function Reference(vertexId, triangleId) {
  74840. this.vertexId = vertexId;
  74841. this.triangleId = triangleId;
  74842. }
  74843. return Reference;
  74844. }());
  74845. BABYLON.Reference = Reference;
  74846. /**
  74847. * An implementation of the Quadratic Error simplification algorithm.
  74848. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  74849. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  74850. * @author RaananW
  74851. */
  74852. var QuadraticErrorSimplification = /** @class */ (function () {
  74853. function QuadraticErrorSimplification(_mesh) {
  74854. this._mesh = _mesh;
  74855. this.syncIterations = 5000;
  74856. this.aggressiveness = 7;
  74857. this.decimationIterations = 100;
  74858. this.boundingBoxEpsilon = BABYLON.Epsilon;
  74859. }
  74860. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  74861. var _this = this;
  74862. this.initDecimatedMesh();
  74863. //iterating through the submeshes array, one after the other.
  74864. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  74865. _this.initWithMesh(loop.index, function () {
  74866. _this.runDecimation(settings, loop.index, function () {
  74867. loop.executeNext();
  74868. });
  74869. }, settings.optimizeMesh);
  74870. }, function () {
  74871. setTimeout(function () {
  74872. successCallback(_this._reconstructedMesh);
  74873. }, 0);
  74874. });
  74875. };
  74876. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  74877. var _this = this;
  74878. var targetCount = ~~(this.triangles.length * settings.quality);
  74879. var deletedTriangles = 0;
  74880. var triangleCount = this.triangles.length;
  74881. var iterationFunction = function (iteration, callback) {
  74882. setTimeout(function () {
  74883. if (iteration % 5 === 0) {
  74884. _this.updateMesh(iteration === 0);
  74885. }
  74886. for (var i = 0; i < _this.triangles.length; ++i) {
  74887. _this.triangles[i].isDirty = false;
  74888. }
  74889. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  74890. var trianglesIterator = function (i) {
  74891. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  74892. var t = _this.triangles[tIdx];
  74893. if (!t)
  74894. return;
  74895. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  74896. return;
  74897. }
  74898. for (var j = 0; j < 3; ++j) {
  74899. if (t.error[j] < threshold) {
  74900. var deleted0 = [];
  74901. var deleted1 = [];
  74902. var v0 = t.vertices[j];
  74903. var v1 = t.vertices[(j + 1) % 3];
  74904. if (v0.isBorder || v1.isBorder)
  74905. continue;
  74906. var p = BABYLON.Vector3.Zero();
  74907. var n = BABYLON.Vector3.Zero();
  74908. var uv = BABYLON.Vector2.Zero();
  74909. var color = new BABYLON.Color4(0, 0, 0, 1);
  74910. _this.calculateError(v0, v1, p, n, uv, color);
  74911. var delTr = new Array();
  74912. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  74913. continue;
  74914. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  74915. continue;
  74916. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  74917. continue;
  74918. var uniqueArray = new Array();
  74919. delTr.forEach(function (deletedT) {
  74920. if (uniqueArray.indexOf(deletedT) === -1) {
  74921. deletedT.deletePending = true;
  74922. uniqueArray.push(deletedT);
  74923. }
  74924. });
  74925. if (uniqueArray.length % 2 !== 0) {
  74926. continue;
  74927. }
  74928. v0.q = v1.q.add(v0.q);
  74929. v0.updatePosition(p);
  74930. var tStart = _this.references.length;
  74931. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  74932. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  74933. var tCount = _this.references.length - tStart;
  74934. if (tCount <= v0.triangleCount) {
  74935. if (tCount) {
  74936. for (var c = 0; c < tCount; c++) {
  74937. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  74938. }
  74939. }
  74940. }
  74941. else {
  74942. v0.triangleStart = tStart;
  74943. }
  74944. v0.triangleCount = tCount;
  74945. break;
  74946. }
  74947. }
  74948. };
  74949. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  74950. }, 0);
  74951. };
  74952. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  74953. if (triangleCount - deletedTriangles <= targetCount)
  74954. loop.breakLoop();
  74955. else {
  74956. iterationFunction(loop.index, function () {
  74957. loop.executeNext();
  74958. });
  74959. }
  74960. }, function () {
  74961. setTimeout(function () {
  74962. //reconstruct this part of the mesh
  74963. _this.reconstructMesh(submeshIndex);
  74964. successCallback();
  74965. }, 0);
  74966. });
  74967. };
  74968. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  74969. var _this = this;
  74970. this.vertices = [];
  74971. this.triangles = [];
  74972. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  74973. var indices = this._mesh.getIndices();
  74974. var submesh = this._mesh.subMeshes[submeshIndex];
  74975. var findInVertices = function (positionToSearch) {
  74976. if (optimizeMesh) {
  74977. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  74978. if (_this.vertices[ii].position.equals(positionToSearch)) {
  74979. return _this.vertices[ii];
  74980. }
  74981. }
  74982. }
  74983. return null;
  74984. };
  74985. var vertexReferences = [];
  74986. var vertexInit = function (i) {
  74987. if (!positionData) {
  74988. return;
  74989. }
  74990. var offset = i + submesh.verticesStart;
  74991. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  74992. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  74993. vertex.originalOffsets.push(offset);
  74994. if (vertex.id === _this.vertices.length) {
  74995. _this.vertices.push(vertex);
  74996. }
  74997. vertexReferences.push(vertex.id);
  74998. };
  74999. //var totalVertices = mesh.getTotalVertices();
  75000. var totalVertices = submesh.verticesCount;
  75001. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  75002. var indicesInit = function (i) {
  75003. if (!indices) {
  75004. return;
  75005. }
  75006. var offset = (submesh.indexStart / 3) + i;
  75007. var pos = (offset * 3);
  75008. var i0 = indices[pos + 0];
  75009. var i1 = indices[pos + 1];
  75010. var i2 = indices[pos + 2];
  75011. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  75012. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  75013. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  75014. var triangle = new DecimationTriangle([v0, v1, v2]);
  75015. triangle.originalOffset = pos;
  75016. _this.triangles.push(triangle);
  75017. };
  75018. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  75019. _this.init(callback);
  75020. });
  75021. });
  75022. };
  75023. QuadraticErrorSimplification.prototype.init = function (callback) {
  75024. var _this = this;
  75025. var triangleInit1 = function (i) {
  75026. var t = _this.triangles[i];
  75027. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  75028. for (var j = 0; j < 3; j++) {
  75029. 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))));
  75030. }
  75031. };
  75032. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  75033. var triangleInit2 = function (i) {
  75034. var t = _this.triangles[i];
  75035. for (var j = 0; j < 3; ++j) {
  75036. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  75037. }
  75038. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  75039. };
  75040. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  75041. callback();
  75042. });
  75043. });
  75044. };
  75045. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  75046. var newTriangles = [];
  75047. var i;
  75048. for (i = 0; i < this.vertices.length; ++i) {
  75049. this.vertices[i].triangleCount = 0;
  75050. }
  75051. var t;
  75052. var j;
  75053. for (i = 0; i < this.triangles.length; ++i) {
  75054. if (!this.triangles[i].deleted) {
  75055. t = this.triangles[i];
  75056. for (j = 0; j < 3; ++j) {
  75057. t.vertices[j].triangleCount = 1;
  75058. }
  75059. newTriangles.push(t);
  75060. }
  75061. }
  75062. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  75063. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  75064. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  75065. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  75066. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  75067. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  75068. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  75069. var vertexCount = 0;
  75070. for (i = 0; i < this.vertices.length; ++i) {
  75071. var vertex = this.vertices[i];
  75072. vertex.id = vertexCount;
  75073. if (vertex.triangleCount) {
  75074. vertex.originalOffsets.forEach(function (originalOffset) {
  75075. if (!normalData) {
  75076. return;
  75077. }
  75078. newPositionData.push(vertex.position.x);
  75079. newPositionData.push(vertex.position.y);
  75080. newPositionData.push(vertex.position.z);
  75081. newNormalData.push(normalData[originalOffset * 3]);
  75082. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  75083. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  75084. if (uvs && uvs.length) {
  75085. newUVsData.push(uvs[(originalOffset * 2)]);
  75086. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  75087. }
  75088. else if (colorsData && colorsData.length) {
  75089. newColorsData.push(colorsData[(originalOffset * 4)]);
  75090. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  75091. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  75092. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  75093. }
  75094. ++vertexCount;
  75095. });
  75096. }
  75097. }
  75098. var startingIndex = this._reconstructedMesh.getTotalIndices();
  75099. var startingVertex = this._reconstructedMesh.getTotalVertices();
  75100. var submeshesArray = this._reconstructedMesh.subMeshes;
  75101. this._reconstructedMesh.subMeshes = [];
  75102. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  75103. var originalIndices = this._mesh.getIndices();
  75104. for (i = 0; i < newTriangles.length; ++i) {
  75105. t = newTriangles[i]; //now get the new referencing point for each vertex
  75106. [0, 1, 2].forEach(function (idx) {
  75107. var id = originalIndices[t.originalOffset + idx];
  75108. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  75109. if (offset < 0)
  75110. offset = 0;
  75111. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  75112. });
  75113. }
  75114. //overwriting the old vertex buffers and indices.
  75115. this._reconstructedMesh.setIndices(newIndicesArray);
  75116. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  75117. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  75118. if (newUVsData.length > 0)
  75119. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  75120. if (newColorsData.length > 0)
  75121. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  75122. //create submesh
  75123. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  75124. if (submeshIndex > 0) {
  75125. this._reconstructedMesh.subMeshes = [];
  75126. submeshesArray.forEach(function (submesh) {
  75127. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  75128. });
  75129. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  75130. }
  75131. };
  75132. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  75133. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  75134. this._reconstructedMesh.material = this._mesh.material;
  75135. this._reconstructedMesh.parent = this._mesh.parent;
  75136. this._reconstructedMesh.isVisible = false;
  75137. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  75138. };
  75139. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  75140. for (var i = 0; i < vertex1.triangleCount; ++i) {
  75141. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  75142. if (t.deleted)
  75143. continue;
  75144. var s = this.references[vertex1.triangleStart + i].vertexId;
  75145. var v1 = t.vertices[(s + 1) % 3];
  75146. var v2 = t.vertices[(s + 2) % 3];
  75147. if ((v1 === vertex2 || v2 === vertex2)) {
  75148. deletedArray[i] = true;
  75149. delTr.push(t);
  75150. continue;
  75151. }
  75152. var d1 = v1.position.subtract(point);
  75153. d1 = d1.normalize();
  75154. var d2 = v2.position.subtract(point);
  75155. d2 = d2.normalize();
  75156. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  75157. return true;
  75158. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  75159. deletedArray[i] = false;
  75160. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  75161. return true;
  75162. }
  75163. return false;
  75164. };
  75165. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  75166. var newDeleted = deletedTriangles;
  75167. for (var i = 0; i < vertex.triangleCount; ++i) {
  75168. var ref = this.references[vertex.triangleStart + i];
  75169. var t = this.triangles[ref.triangleId];
  75170. if (t.deleted)
  75171. continue;
  75172. if (deletedArray[i] && t.deletePending) {
  75173. t.deleted = true;
  75174. newDeleted++;
  75175. continue;
  75176. }
  75177. t.vertices[ref.vertexId] = origVertex;
  75178. t.isDirty = true;
  75179. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  75180. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  75181. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  75182. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  75183. this.references.push(ref);
  75184. }
  75185. return newDeleted;
  75186. };
  75187. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  75188. for (var i = 0; i < this.vertices.length; ++i) {
  75189. var vCount = [];
  75190. var vId = [];
  75191. var v = this.vertices[i];
  75192. var j;
  75193. for (j = 0; j < v.triangleCount; ++j) {
  75194. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  75195. for (var ii = 0; ii < 3; ii++) {
  75196. var ofs = 0;
  75197. var vv = triangle.vertices[ii];
  75198. while (ofs < vCount.length) {
  75199. if (vId[ofs] === vv.id)
  75200. break;
  75201. ++ofs;
  75202. }
  75203. if (ofs === vCount.length) {
  75204. vCount.push(1);
  75205. vId.push(vv.id);
  75206. }
  75207. else {
  75208. vCount[ofs]++;
  75209. }
  75210. }
  75211. }
  75212. for (j = 0; j < vCount.length; ++j) {
  75213. if (vCount[j] === 1) {
  75214. this.vertices[vId[j]].isBorder = true;
  75215. }
  75216. else {
  75217. this.vertices[vId[j]].isBorder = false;
  75218. }
  75219. }
  75220. }
  75221. };
  75222. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  75223. if (identifyBorders === void 0) { identifyBorders = false; }
  75224. var i;
  75225. if (!identifyBorders) {
  75226. var newTrianglesVector = [];
  75227. for (i = 0; i < this.triangles.length; ++i) {
  75228. if (!this.triangles[i].deleted) {
  75229. newTrianglesVector.push(this.triangles[i]);
  75230. }
  75231. }
  75232. this.triangles = newTrianglesVector;
  75233. }
  75234. for (i = 0; i < this.vertices.length; ++i) {
  75235. this.vertices[i].triangleCount = 0;
  75236. this.vertices[i].triangleStart = 0;
  75237. }
  75238. var t;
  75239. var j;
  75240. var v;
  75241. for (i = 0; i < this.triangles.length; ++i) {
  75242. t = this.triangles[i];
  75243. for (j = 0; j < 3; ++j) {
  75244. v = t.vertices[j];
  75245. v.triangleCount++;
  75246. }
  75247. }
  75248. var tStart = 0;
  75249. for (i = 0; i < this.vertices.length; ++i) {
  75250. this.vertices[i].triangleStart = tStart;
  75251. tStart += this.vertices[i].triangleCount;
  75252. this.vertices[i].triangleCount = 0;
  75253. }
  75254. var newReferences = new Array(this.triangles.length * 3);
  75255. for (i = 0; i < this.triangles.length; ++i) {
  75256. t = this.triangles[i];
  75257. for (j = 0; j < 3; ++j) {
  75258. v = t.vertices[j];
  75259. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  75260. v.triangleCount++;
  75261. }
  75262. }
  75263. this.references = newReferences;
  75264. if (identifyBorders) {
  75265. this.identifyBorder();
  75266. }
  75267. };
  75268. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  75269. var x = point.x;
  75270. var y = point.y;
  75271. var z = point.z;
  75272. 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
  75273. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  75274. };
  75275. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  75276. var q = vertex1.q.add(vertex2.q);
  75277. var border = vertex1.isBorder && vertex2.isBorder;
  75278. var error = 0;
  75279. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  75280. if (qDet !== 0 && !border) {
  75281. if (!pointResult) {
  75282. pointResult = BABYLON.Vector3.Zero();
  75283. }
  75284. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  75285. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  75286. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  75287. error = this.vertexError(q, pointResult);
  75288. }
  75289. else {
  75290. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  75291. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  75292. var error1 = this.vertexError(q, vertex1.position);
  75293. var error2 = this.vertexError(q, vertex2.position);
  75294. var error3 = this.vertexError(q, p3);
  75295. error = Math.min(error1, error2, error3);
  75296. if (error === error1) {
  75297. if (pointResult) {
  75298. pointResult.copyFrom(vertex1.position);
  75299. }
  75300. }
  75301. else if (error === error2) {
  75302. if (pointResult) {
  75303. pointResult.copyFrom(vertex2.position);
  75304. }
  75305. }
  75306. else {
  75307. if (pointResult) {
  75308. pointResult.copyFrom(p3);
  75309. }
  75310. }
  75311. }
  75312. return error;
  75313. };
  75314. return QuadraticErrorSimplification;
  75315. }());
  75316. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  75317. })(BABYLON || (BABYLON = {}));
  75318. //# sourceMappingURL=babylon.meshSimplification.js.map
  75319. var BABYLON;
  75320. (function (BABYLON) {
  75321. var Internals;
  75322. (function (Internals) {
  75323. var MeshLODLevel = /** @class */ (function () {
  75324. function MeshLODLevel(distance, mesh) {
  75325. this.distance = distance;
  75326. this.mesh = mesh;
  75327. }
  75328. return MeshLODLevel;
  75329. }());
  75330. Internals.MeshLODLevel = MeshLODLevel;
  75331. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  75332. })(BABYLON || (BABYLON = {}));
  75333. //# sourceMappingURL=babylon.meshLODLevel.js.map
  75334. var BABYLON;
  75335. (function (BABYLON) {
  75336. // Standard optimizations
  75337. var SceneOptimization = /** @class */ (function () {
  75338. function SceneOptimization(priority) {
  75339. if (priority === void 0) { priority = 0; }
  75340. this.priority = priority;
  75341. this.apply = function (scene) {
  75342. return true; // Return true if everything that can be done was applied
  75343. };
  75344. }
  75345. return SceneOptimization;
  75346. }());
  75347. BABYLON.SceneOptimization = SceneOptimization;
  75348. var TextureOptimization = /** @class */ (function (_super) {
  75349. __extends(TextureOptimization, _super);
  75350. function TextureOptimization(priority, maximumSize) {
  75351. if (priority === void 0) { priority = 0; }
  75352. if (maximumSize === void 0) { maximumSize = 1024; }
  75353. var _this = _super.call(this, priority) || this;
  75354. _this.priority = priority;
  75355. _this.maximumSize = maximumSize;
  75356. _this.apply = function (scene) {
  75357. var allDone = true;
  75358. for (var index = 0; index < scene.textures.length; index++) {
  75359. var texture = scene.textures[index];
  75360. if (!texture.canRescale || texture.getContext) {
  75361. continue;
  75362. }
  75363. var currentSize = texture.getSize();
  75364. var maxDimension = Math.max(currentSize.width, currentSize.height);
  75365. if (maxDimension > _this.maximumSize) {
  75366. texture.scale(0.5);
  75367. allDone = false;
  75368. }
  75369. }
  75370. return allDone;
  75371. };
  75372. return _this;
  75373. }
  75374. return TextureOptimization;
  75375. }(SceneOptimization));
  75376. BABYLON.TextureOptimization = TextureOptimization;
  75377. var HardwareScalingOptimization = /** @class */ (function (_super) {
  75378. __extends(HardwareScalingOptimization, _super);
  75379. function HardwareScalingOptimization(priority, maximumScale) {
  75380. if (priority === void 0) { priority = 0; }
  75381. if (maximumScale === void 0) { maximumScale = 2; }
  75382. var _this = _super.call(this, priority) || this;
  75383. _this.priority = priority;
  75384. _this.maximumScale = maximumScale;
  75385. _this._currentScale = 1;
  75386. _this.apply = function (scene) {
  75387. _this._currentScale++;
  75388. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  75389. return _this._currentScale >= _this.maximumScale;
  75390. };
  75391. return _this;
  75392. }
  75393. return HardwareScalingOptimization;
  75394. }(SceneOptimization));
  75395. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  75396. var ShadowsOptimization = /** @class */ (function (_super) {
  75397. __extends(ShadowsOptimization, _super);
  75398. function ShadowsOptimization() {
  75399. var _this = _super !== null && _super.apply(this, arguments) || this;
  75400. _this.apply = function (scene) {
  75401. scene.shadowsEnabled = false;
  75402. return true;
  75403. };
  75404. return _this;
  75405. }
  75406. return ShadowsOptimization;
  75407. }(SceneOptimization));
  75408. BABYLON.ShadowsOptimization = ShadowsOptimization;
  75409. var PostProcessesOptimization = /** @class */ (function (_super) {
  75410. __extends(PostProcessesOptimization, _super);
  75411. function PostProcessesOptimization() {
  75412. var _this = _super !== null && _super.apply(this, arguments) || this;
  75413. _this.apply = function (scene) {
  75414. scene.postProcessesEnabled = false;
  75415. return true;
  75416. };
  75417. return _this;
  75418. }
  75419. return PostProcessesOptimization;
  75420. }(SceneOptimization));
  75421. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  75422. var LensFlaresOptimization = /** @class */ (function (_super) {
  75423. __extends(LensFlaresOptimization, _super);
  75424. function LensFlaresOptimization() {
  75425. var _this = _super !== null && _super.apply(this, arguments) || this;
  75426. _this.apply = function (scene) {
  75427. scene.lensFlaresEnabled = false;
  75428. return true;
  75429. };
  75430. return _this;
  75431. }
  75432. return LensFlaresOptimization;
  75433. }(SceneOptimization));
  75434. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  75435. var ParticlesOptimization = /** @class */ (function (_super) {
  75436. __extends(ParticlesOptimization, _super);
  75437. function ParticlesOptimization() {
  75438. var _this = _super !== null && _super.apply(this, arguments) || this;
  75439. _this.apply = function (scene) {
  75440. scene.particlesEnabled = false;
  75441. return true;
  75442. };
  75443. return _this;
  75444. }
  75445. return ParticlesOptimization;
  75446. }(SceneOptimization));
  75447. BABYLON.ParticlesOptimization = ParticlesOptimization;
  75448. var RenderTargetsOptimization = /** @class */ (function (_super) {
  75449. __extends(RenderTargetsOptimization, _super);
  75450. function RenderTargetsOptimization() {
  75451. var _this = _super !== null && _super.apply(this, arguments) || this;
  75452. _this.apply = function (scene) {
  75453. scene.renderTargetsEnabled = false;
  75454. return true;
  75455. };
  75456. return _this;
  75457. }
  75458. return RenderTargetsOptimization;
  75459. }(SceneOptimization));
  75460. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  75461. var MergeMeshesOptimization = /** @class */ (function (_super) {
  75462. __extends(MergeMeshesOptimization, _super);
  75463. function MergeMeshesOptimization() {
  75464. var _this = _super !== null && _super.apply(this, arguments) || this;
  75465. _this._canBeMerged = function (abstractMesh) {
  75466. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  75467. return false;
  75468. }
  75469. var mesh = abstractMesh;
  75470. if (!mesh.isVisible || !mesh.isEnabled()) {
  75471. return false;
  75472. }
  75473. if (mesh.instances.length > 0) {
  75474. return false;
  75475. }
  75476. if (mesh.skeleton || mesh.hasLODLevels) {
  75477. return false;
  75478. }
  75479. if (mesh.parent) {
  75480. return false;
  75481. }
  75482. return true;
  75483. };
  75484. _this.apply = function (scene, updateSelectionTree) {
  75485. var globalPool = scene.meshes.slice(0);
  75486. var globalLength = globalPool.length;
  75487. for (var index = 0; index < globalLength; index++) {
  75488. var currentPool = new Array();
  75489. var current = globalPool[index];
  75490. // Checks
  75491. if (!_this._canBeMerged(current)) {
  75492. continue;
  75493. }
  75494. currentPool.push(current);
  75495. // Find compatible meshes
  75496. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  75497. var otherMesh = globalPool[subIndex];
  75498. if (!_this._canBeMerged(otherMesh)) {
  75499. continue;
  75500. }
  75501. if (otherMesh.material !== current.material) {
  75502. continue;
  75503. }
  75504. if (otherMesh.checkCollisions !== current.checkCollisions) {
  75505. continue;
  75506. }
  75507. currentPool.push(otherMesh);
  75508. globalLength--;
  75509. globalPool.splice(subIndex, 1);
  75510. subIndex--;
  75511. }
  75512. if (currentPool.length < 2) {
  75513. continue;
  75514. }
  75515. // Merge meshes
  75516. BABYLON.Mesh.MergeMeshes(currentPool);
  75517. }
  75518. if (updateSelectionTree != undefined) {
  75519. if (updateSelectionTree) {
  75520. scene.createOrUpdateSelectionOctree();
  75521. }
  75522. }
  75523. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  75524. scene.createOrUpdateSelectionOctree();
  75525. }
  75526. return true;
  75527. };
  75528. return _this;
  75529. }
  75530. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  75531. get: function () {
  75532. return MergeMeshesOptimization._UpdateSelectionTree;
  75533. },
  75534. set: function (value) {
  75535. MergeMeshesOptimization._UpdateSelectionTree = value;
  75536. },
  75537. enumerable: true,
  75538. configurable: true
  75539. });
  75540. MergeMeshesOptimization._UpdateSelectionTree = false;
  75541. return MergeMeshesOptimization;
  75542. }(SceneOptimization));
  75543. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  75544. // Options
  75545. var SceneOptimizerOptions = /** @class */ (function () {
  75546. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  75547. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  75548. if (trackerDuration === void 0) { trackerDuration = 2000; }
  75549. this.targetFrameRate = targetFrameRate;
  75550. this.trackerDuration = trackerDuration;
  75551. this.optimizations = new Array();
  75552. }
  75553. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  75554. var result = new SceneOptimizerOptions(targetFrameRate);
  75555. var priority = 0;
  75556. result.optimizations.push(new MergeMeshesOptimization(priority));
  75557. result.optimizations.push(new ShadowsOptimization(priority));
  75558. result.optimizations.push(new LensFlaresOptimization(priority));
  75559. // Next priority
  75560. priority++;
  75561. result.optimizations.push(new PostProcessesOptimization(priority));
  75562. result.optimizations.push(new ParticlesOptimization(priority));
  75563. // Next priority
  75564. priority++;
  75565. result.optimizations.push(new TextureOptimization(priority, 1024));
  75566. return result;
  75567. };
  75568. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  75569. var result = new SceneOptimizerOptions(targetFrameRate);
  75570. var priority = 0;
  75571. result.optimizations.push(new MergeMeshesOptimization(priority));
  75572. result.optimizations.push(new ShadowsOptimization(priority));
  75573. result.optimizations.push(new LensFlaresOptimization(priority));
  75574. // Next priority
  75575. priority++;
  75576. result.optimizations.push(new PostProcessesOptimization(priority));
  75577. result.optimizations.push(new ParticlesOptimization(priority));
  75578. // Next priority
  75579. priority++;
  75580. result.optimizations.push(new TextureOptimization(priority, 512));
  75581. // Next priority
  75582. priority++;
  75583. result.optimizations.push(new RenderTargetsOptimization(priority));
  75584. // Next priority
  75585. priority++;
  75586. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  75587. return result;
  75588. };
  75589. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  75590. var result = new SceneOptimizerOptions(targetFrameRate);
  75591. var priority = 0;
  75592. result.optimizations.push(new MergeMeshesOptimization(priority));
  75593. result.optimizations.push(new ShadowsOptimization(priority));
  75594. result.optimizations.push(new LensFlaresOptimization(priority));
  75595. // Next priority
  75596. priority++;
  75597. result.optimizations.push(new PostProcessesOptimization(priority));
  75598. result.optimizations.push(new ParticlesOptimization(priority));
  75599. // Next priority
  75600. priority++;
  75601. result.optimizations.push(new TextureOptimization(priority, 256));
  75602. // Next priority
  75603. priority++;
  75604. result.optimizations.push(new RenderTargetsOptimization(priority));
  75605. // Next priority
  75606. priority++;
  75607. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  75608. return result;
  75609. };
  75610. return SceneOptimizerOptions;
  75611. }());
  75612. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  75613. // Scene optimizer tool
  75614. var SceneOptimizer = /** @class */ (function () {
  75615. function SceneOptimizer() {
  75616. }
  75617. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  75618. // TODO: add an epsilon
  75619. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  75620. if (onSuccess) {
  75621. onSuccess();
  75622. }
  75623. return;
  75624. }
  75625. // Apply current level of optimizations
  75626. var allDone = true;
  75627. var noOptimizationApplied = true;
  75628. for (var index = 0; index < options.optimizations.length; index++) {
  75629. var optimization = options.optimizations[index];
  75630. if (optimization.priority === currentPriorityLevel) {
  75631. noOptimizationApplied = false;
  75632. allDone = allDone && optimization.apply(scene);
  75633. }
  75634. }
  75635. // If no optimization was applied, this is a failure :(
  75636. if (noOptimizationApplied) {
  75637. if (onFailure) {
  75638. onFailure();
  75639. }
  75640. return;
  75641. }
  75642. // If all optimizations were done, move to next level
  75643. if (allDone) {
  75644. currentPriorityLevel++;
  75645. }
  75646. // Let's the system running for a specific amount of time before checking FPS
  75647. scene.executeWhenReady(function () {
  75648. setTimeout(function () {
  75649. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  75650. }, options.trackerDuration);
  75651. });
  75652. };
  75653. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  75654. if (!options) {
  75655. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  75656. }
  75657. // Let's the system running for a specific amount of time before checking FPS
  75658. scene.executeWhenReady(function () {
  75659. setTimeout(function () {
  75660. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  75661. }, options.trackerDuration);
  75662. });
  75663. };
  75664. return SceneOptimizer;
  75665. }());
  75666. BABYLON.SceneOptimizer = SceneOptimizer;
  75667. })(BABYLON || (BABYLON = {}));
  75668. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  75669. var BABYLON;
  75670. (function (BABYLON) {
  75671. var OutlineRenderer = /** @class */ (function () {
  75672. function OutlineRenderer(scene) {
  75673. this.zOffset = 1;
  75674. this._scene = scene;
  75675. }
  75676. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  75677. var _this = this;
  75678. if (useOverlay === void 0) { useOverlay = false; }
  75679. var scene = this._scene;
  75680. var engine = this._scene.getEngine();
  75681. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  75682. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  75683. return;
  75684. }
  75685. var mesh = subMesh.getRenderingMesh();
  75686. var material = subMesh.getMaterial();
  75687. if (!material || !scene.activeCamera) {
  75688. return;
  75689. }
  75690. engine.enableEffect(this._effect);
  75691. // Logarithmic depth
  75692. if (material.useLogarithmicDepth) {
  75693. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  75694. }
  75695. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  75696. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  75697. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  75698. // Bones
  75699. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  75700. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  75701. }
  75702. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  75703. // Alpha test
  75704. if (material && material.needAlphaTesting()) {
  75705. var alphaTexture = material.getAlphaTestTexture();
  75706. if (alphaTexture) {
  75707. this._effect.setTexture("diffuseSampler", alphaTexture);
  75708. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  75709. }
  75710. }
  75711. engine.setZOffset(-this.zOffset);
  75712. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  75713. engine.setZOffset(0);
  75714. };
  75715. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  75716. var defines = [];
  75717. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  75718. var mesh = subMesh.getMesh();
  75719. var material = subMesh.getMaterial();
  75720. if (material) {
  75721. // Alpha test
  75722. if (material.needAlphaTesting()) {
  75723. defines.push("#define ALPHATEST");
  75724. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  75725. attribs.push(BABYLON.VertexBuffer.UVKind);
  75726. defines.push("#define UV1");
  75727. }
  75728. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  75729. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  75730. defines.push("#define UV2");
  75731. }
  75732. }
  75733. //Logarithmic depth
  75734. if (material.useLogarithmicDepth) {
  75735. defines.push("#define LOGARITHMICDEPTH");
  75736. }
  75737. }
  75738. // Bones
  75739. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  75740. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  75741. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  75742. if (mesh.numBoneInfluencers > 4) {
  75743. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  75744. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  75745. }
  75746. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  75747. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  75748. }
  75749. else {
  75750. defines.push("#define NUM_BONE_INFLUENCERS 0");
  75751. }
  75752. // Instances
  75753. if (useInstances) {
  75754. defines.push("#define INSTANCES");
  75755. attribs.push("world0");
  75756. attribs.push("world1");
  75757. attribs.push("world2");
  75758. attribs.push("world3");
  75759. }
  75760. // Get correct effect
  75761. var join = defines.join("\n");
  75762. if (this._cachedDefines !== join) {
  75763. this._cachedDefines = join;
  75764. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  75765. }
  75766. return this._effect.isReady();
  75767. };
  75768. return OutlineRenderer;
  75769. }());
  75770. BABYLON.OutlineRenderer = OutlineRenderer;
  75771. })(BABYLON || (BABYLON = {}));
  75772. //# sourceMappingURL=babylon.outlineRenderer.js.map
  75773. var BABYLON;
  75774. (function (BABYLON) {
  75775. var FaceAdjacencies = /** @class */ (function () {
  75776. function FaceAdjacencies() {
  75777. this.edges = new Array();
  75778. this.edgesConnectedCount = 0;
  75779. }
  75780. return FaceAdjacencies;
  75781. }());
  75782. var EdgesRenderer = /** @class */ (function () {
  75783. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  75784. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  75785. if (epsilon === void 0) { epsilon = 0.95; }
  75786. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  75787. this.edgesWidthScalerForOrthographic = 1000.0;
  75788. this.edgesWidthScalerForPerspective = 50.0;
  75789. this._linesPositions = new Array();
  75790. this._linesNormals = new Array();
  75791. this._linesIndices = new Array();
  75792. this._buffers = {};
  75793. this._checkVerticesInsteadOfIndices = false;
  75794. this._source = source;
  75795. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  75796. this._epsilon = epsilon;
  75797. this._prepareRessources();
  75798. this._generateEdgesLines();
  75799. }
  75800. EdgesRenderer.prototype._prepareRessources = function () {
  75801. if (this._lineShader) {
  75802. return;
  75803. }
  75804. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  75805. attributes: ["position", "normal"],
  75806. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  75807. });
  75808. this._lineShader.disableDepthWrite = true;
  75809. this._lineShader.backFaceCulling = false;
  75810. };
  75811. EdgesRenderer.prototype._rebuild = function () {
  75812. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  75813. if (buffer) {
  75814. buffer._rebuild();
  75815. }
  75816. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  75817. if (buffer) {
  75818. buffer._rebuild();
  75819. }
  75820. var scene = this._source.getScene();
  75821. var engine = scene.getEngine();
  75822. this._ib = engine.createIndexBuffer(this._linesIndices);
  75823. };
  75824. EdgesRenderer.prototype.dispose = function () {
  75825. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  75826. if (buffer) {
  75827. buffer.dispose();
  75828. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  75829. }
  75830. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  75831. if (buffer) {
  75832. buffer.dispose();
  75833. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  75834. }
  75835. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  75836. this._lineShader.dispose();
  75837. };
  75838. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  75839. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  75840. return 0;
  75841. }
  75842. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  75843. return 1;
  75844. }
  75845. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  75846. return 2;
  75847. }
  75848. return -1;
  75849. };
  75850. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  75851. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  75852. return 0;
  75853. }
  75854. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  75855. return 1;
  75856. }
  75857. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  75858. return 2;
  75859. }
  75860. return -1;
  75861. };
  75862. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  75863. var needToCreateLine;
  75864. if (edge === undefined) {
  75865. needToCreateLine = true;
  75866. }
  75867. else {
  75868. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  75869. needToCreateLine = dotProduct < this._epsilon;
  75870. }
  75871. if (needToCreateLine) {
  75872. var offset = this._linesPositions.length / 3;
  75873. var normal = p0.subtract(p1);
  75874. normal.normalize();
  75875. // Positions
  75876. this._linesPositions.push(p0.x);
  75877. this._linesPositions.push(p0.y);
  75878. this._linesPositions.push(p0.z);
  75879. this._linesPositions.push(p0.x);
  75880. this._linesPositions.push(p0.y);
  75881. this._linesPositions.push(p0.z);
  75882. this._linesPositions.push(p1.x);
  75883. this._linesPositions.push(p1.y);
  75884. this._linesPositions.push(p1.z);
  75885. this._linesPositions.push(p1.x);
  75886. this._linesPositions.push(p1.y);
  75887. this._linesPositions.push(p1.z);
  75888. // Normals
  75889. this._linesNormals.push(p1.x);
  75890. this._linesNormals.push(p1.y);
  75891. this._linesNormals.push(p1.z);
  75892. this._linesNormals.push(-1);
  75893. this._linesNormals.push(p1.x);
  75894. this._linesNormals.push(p1.y);
  75895. this._linesNormals.push(p1.z);
  75896. this._linesNormals.push(1);
  75897. this._linesNormals.push(p0.x);
  75898. this._linesNormals.push(p0.y);
  75899. this._linesNormals.push(p0.z);
  75900. this._linesNormals.push(-1);
  75901. this._linesNormals.push(p0.x);
  75902. this._linesNormals.push(p0.y);
  75903. this._linesNormals.push(p0.z);
  75904. this._linesNormals.push(1);
  75905. // Indices
  75906. this._linesIndices.push(offset);
  75907. this._linesIndices.push(offset + 1);
  75908. this._linesIndices.push(offset + 2);
  75909. this._linesIndices.push(offset);
  75910. this._linesIndices.push(offset + 2);
  75911. this._linesIndices.push(offset + 3);
  75912. }
  75913. };
  75914. EdgesRenderer.prototype._generateEdgesLines = function () {
  75915. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  75916. var indices = this._source.getIndices();
  75917. if (!indices || !positions) {
  75918. return;
  75919. }
  75920. // First let's find adjacencies
  75921. var adjacencies = new Array();
  75922. var faceNormals = new Array();
  75923. var index;
  75924. var faceAdjacencies;
  75925. // Prepare faces
  75926. for (index = 0; index < indices.length; index += 3) {
  75927. faceAdjacencies = new FaceAdjacencies();
  75928. var p0Index = indices[index];
  75929. var p1Index = indices[index + 1];
  75930. var p2Index = indices[index + 2];
  75931. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  75932. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  75933. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  75934. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  75935. faceNormal.normalize();
  75936. faceNormals.push(faceNormal);
  75937. adjacencies.push(faceAdjacencies);
  75938. }
  75939. // Scan
  75940. for (index = 0; index < adjacencies.length; index++) {
  75941. faceAdjacencies = adjacencies[index];
  75942. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  75943. var otherFaceAdjacencies = adjacencies[otherIndex];
  75944. if (faceAdjacencies.edgesConnectedCount === 3) {
  75945. break;
  75946. }
  75947. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  75948. continue;
  75949. }
  75950. var otherP0 = indices[otherIndex * 3];
  75951. var otherP1 = indices[otherIndex * 3 + 1];
  75952. var otherP2 = indices[otherIndex * 3 + 2];
  75953. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  75954. var otherEdgeIndex = 0;
  75955. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  75956. continue;
  75957. }
  75958. switch (edgeIndex) {
  75959. case 0:
  75960. if (this._checkVerticesInsteadOfIndices) {
  75961. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  75962. }
  75963. else {
  75964. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  75965. }
  75966. break;
  75967. case 1:
  75968. if (this._checkVerticesInsteadOfIndices) {
  75969. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  75970. }
  75971. else {
  75972. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  75973. }
  75974. break;
  75975. case 2:
  75976. if (this._checkVerticesInsteadOfIndices) {
  75977. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  75978. }
  75979. else {
  75980. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  75981. }
  75982. break;
  75983. }
  75984. if (otherEdgeIndex === -1) {
  75985. continue;
  75986. }
  75987. faceAdjacencies.edges[edgeIndex] = otherIndex;
  75988. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  75989. faceAdjacencies.edgesConnectedCount++;
  75990. otherFaceAdjacencies.edgesConnectedCount++;
  75991. if (faceAdjacencies.edgesConnectedCount === 3) {
  75992. break;
  75993. }
  75994. }
  75995. }
  75996. }
  75997. // Create lines
  75998. for (index = 0; index < adjacencies.length; index++) {
  75999. // 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
  76000. var current = adjacencies[index];
  76001. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  76002. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  76003. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  76004. }
  76005. // Merge into a single mesh
  76006. var engine = this._source.getScene().getEngine();
  76007. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  76008. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  76009. this._ib = engine.createIndexBuffer(this._linesIndices);
  76010. this._indicesCount = this._linesIndices.length;
  76011. };
  76012. EdgesRenderer.prototype.render = function () {
  76013. var scene = this._source.getScene();
  76014. if (!this._lineShader.isReady() || !scene.activeCamera) {
  76015. return;
  76016. }
  76017. var engine = scene.getEngine();
  76018. this._lineShader._preBind();
  76019. // VBOs
  76020. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  76021. scene.resetCachedMaterial();
  76022. this._lineShader.setColor4("color", this._source.edgesColor);
  76023. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  76024. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  76025. }
  76026. else {
  76027. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  76028. }
  76029. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  76030. this._lineShader.bind(this._source.getWorldMatrix());
  76031. // Draw order
  76032. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  76033. this._lineShader.unbind();
  76034. engine.setDepthWrite(true);
  76035. };
  76036. return EdgesRenderer;
  76037. }());
  76038. BABYLON.EdgesRenderer = EdgesRenderer;
  76039. })(BABYLON || (BABYLON = {}));
  76040. //# sourceMappingURL=babylon.edgesRenderer.js.map
  76041. var BABYLON;
  76042. (function (BABYLON) {
  76043. /**
  76044. * Special Glow Blur post process only blurring the alpha channel
  76045. * It enforces keeping the most luminous color in the color channel.
  76046. */
  76047. var GlowBlurPostProcess = /** @class */ (function (_super) {
  76048. __extends(GlowBlurPostProcess, _super);
  76049. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  76050. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76051. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  76052. _this.direction = direction;
  76053. _this.kernel = kernel;
  76054. _this.onApplyObservable.add(function (effect) {
  76055. effect.setFloat2("screenSize", _this.width, _this.height);
  76056. effect.setVector2("direction", _this.direction);
  76057. effect.setFloat("blurWidth", _this.kernel);
  76058. });
  76059. return _this;
  76060. }
  76061. return GlowBlurPostProcess;
  76062. }(BABYLON.PostProcess));
  76063. /**
  76064. * The highlight layer Helps adding a glow effect around a mesh.
  76065. *
  76066. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  76067. * glowy meshes to your scene.
  76068. *
  76069. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  76070. */
  76071. var HighlightLayer = /** @class */ (function () {
  76072. /**
  76073. * Instantiates a new highlight Layer and references it to the scene..
  76074. * @param name The name of the layer
  76075. * @param scene The scene to use the layer in
  76076. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  76077. */
  76078. function HighlightLayer(name, scene, options) {
  76079. this.name = name;
  76080. this._vertexBuffers = {};
  76081. this._mainTextureDesiredSize = { width: 0, height: 0 };
  76082. this._meshes = {};
  76083. this._maxSize = 0;
  76084. this._shouldRender = false;
  76085. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  76086. this._excludedMeshes = {};
  76087. /**
  76088. * Specifies whether or not the inner glow is ACTIVE in the layer.
  76089. */
  76090. this.innerGlow = true;
  76091. /**
  76092. * Specifies whether or not the outer glow is ACTIVE in the layer.
  76093. */
  76094. this.outerGlow = true;
  76095. /**
  76096. * Specifies wether the highlight layer is enabled or not.
  76097. */
  76098. this.isEnabled = true;
  76099. /**
  76100. * An event triggered when the highlight layer has been disposed.
  76101. * @type {BABYLON.Observable}
  76102. */
  76103. this.onDisposeObservable = new BABYLON.Observable();
  76104. /**
  76105. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  76106. * @type {BABYLON.Observable}
  76107. */
  76108. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  76109. /**
  76110. * An event triggered when the highlight layer is being blurred.
  76111. * @type {BABYLON.Observable}
  76112. */
  76113. this.onBeforeBlurObservable = new BABYLON.Observable();
  76114. /**
  76115. * An event triggered when the highlight layer has been blurred.
  76116. * @type {BABYLON.Observable}
  76117. */
  76118. this.onAfterBlurObservable = new BABYLON.Observable();
  76119. /**
  76120. * An event triggered when the glowing blurred texture is being merged in the scene.
  76121. * @type {BABYLON.Observable}
  76122. */
  76123. this.onBeforeComposeObservable = new BABYLON.Observable();
  76124. /**
  76125. * An event triggered when the glowing blurred texture has been merged in the scene.
  76126. * @type {BABYLON.Observable}
  76127. */
  76128. this.onAfterComposeObservable = new BABYLON.Observable();
  76129. /**
  76130. * An event triggered when the highlight layer changes its size.
  76131. * @type {BABYLON.Observable}
  76132. */
  76133. this.onSizeChangedObservable = new BABYLON.Observable();
  76134. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  76135. var engine = scene.getEngine();
  76136. this._engine = engine;
  76137. this._maxSize = this._engine.getCaps().maxTextureSize;
  76138. this._scene.highlightLayers.push(this);
  76139. // Warn on stencil.
  76140. if (!this._engine.isStencilEnable) {
  76141. 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 }");
  76142. }
  76143. // Adapt options
  76144. this._options = options || {
  76145. mainTextureRatio: 0.5,
  76146. blurTextureSizeRatio: 0.5,
  76147. blurHorizontalSize: 1.0,
  76148. blurVerticalSize: 1.0,
  76149. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  76150. camera: null
  76151. };
  76152. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  76153. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  76154. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  76155. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  76156. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  76157. // VBO
  76158. var vertices = [];
  76159. vertices.push(1, 1);
  76160. vertices.push(-1, 1);
  76161. vertices.push(-1, -1);
  76162. vertices.push(1, -1);
  76163. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  76164. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  76165. this._createIndexBuffer();
  76166. // Effect
  76167. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  76168. // Render target
  76169. this.setMainTextureSize();
  76170. // Create Textures and post processes
  76171. this.createTextureAndPostProcesses();
  76172. }
  76173. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  76174. /**
  76175. * Gets the horizontal size of the blur.
  76176. */
  76177. get: function () {
  76178. return this._horizontalBlurPostprocess.kernel;
  76179. },
  76180. /**
  76181. * Specifies the horizontal size of the blur.
  76182. */
  76183. set: function (value) {
  76184. this._horizontalBlurPostprocess.kernel = value;
  76185. },
  76186. enumerable: true,
  76187. configurable: true
  76188. });
  76189. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  76190. /**
  76191. * Gets the vertical size of the blur.
  76192. */
  76193. get: function () {
  76194. return this._verticalBlurPostprocess.kernel;
  76195. },
  76196. /**
  76197. * Specifies the vertical size of the blur.
  76198. */
  76199. set: function (value) {
  76200. this._verticalBlurPostprocess.kernel = value;
  76201. },
  76202. enumerable: true,
  76203. configurable: true
  76204. });
  76205. Object.defineProperty(HighlightLayer.prototype, "camera", {
  76206. /**
  76207. * Gets the camera attached to the layer.
  76208. */
  76209. get: function () {
  76210. return this._options.camera;
  76211. },
  76212. enumerable: true,
  76213. configurable: true
  76214. });
  76215. HighlightLayer.prototype._createIndexBuffer = function () {
  76216. var engine = this._scene.getEngine();
  76217. // Indices
  76218. var indices = [];
  76219. indices.push(0);
  76220. indices.push(1);
  76221. indices.push(2);
  76222. indices.push(0);
  76223. indices.push(2);
  76224. indices.push(3);
  76225. this._indexBuffer = engine.createIndexBuffer(indices);
  76226. };
  76227. HighlightLayer.prototype._rebuild = function () {
  76228. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76229. if (vb) {
  76230. vb._rebuild();
  76231. }
  76232. this._createIndexBuffer();
  76233. };
  76234. /**
  76235. * Creates the render target textures and post processes used in the highlight layer.
  76236. */
  76237. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  76238. var _this = this;
  76239. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  76240. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  76241. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  76242. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  76243. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  76244. width: this._mainTextureDesiredSize.width,
  76245. height: this._mainTextureDesiredSize.height
  76246. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76247. this._mainTexture.activeCamera = this._options.camera;
  76248. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76249. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76250. this._mainTexture.anisotropicFilteringLevel = 1;
  76251. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  76252. this._mainTexture.renderParticles = false;
  76253. this._mainTexture.renderList = null;
  76254. this._mainTexture.ignoreCameraViewport = true;
  76255. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  76256. width: blurTextureWidth,
  76257. height: blurTextureHeight
  76258. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76259. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76260. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76261. this._blurTexture.anisotropicFilteringLevel = 16;
  76262. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  76263. this._blurTexture.renderParticles = false;
  76264. this._blurTexture.ignoreCameraViewport = true;
  76265. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  76266. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  76267. effect.setTexture("textureSampler", _this._mainTexture);
  76268. });
  76269. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  76270. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  76271. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  76272. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  76273. });
  76274. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  76275. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  76276. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  76277. });
  76278. }
  76279. else {
  76280. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  76281. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  76282. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  76283. });
  76284. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  76285. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  76286. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  76287. });
  76288. }
  76289. this._mainTexture.onAfterUnbindObservable.add(function () {
  76290. _this.onBeforeBlurObservable.notifyObservers(_this);
  76291. var internalTexture = _this._blurTexture.getInternalTexture();
  76292. if (internalTexture) {
  76293. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  76294. }
  76295. _this.onAfterBlurObservable.notifyObservers(_this);
  76296. });
  76297. // Custom render function
  76298. var renderSubMesh = function (subMesh) {
  76299. if (!_this._meshes) {
  76300. return;
  76301. }
  76302. var material = subMesh.getMaterial();
  76303. var mesh = subMesh.getRenderingMesh();
  76304. var scene = _this._scene;
  76305. var engine = scene.getEngine();
  76306. if (!material) {
  76307. return;
  76308. }
  76309. // Do not block in blend mode.
  76310. if (material.needAlphaBlendingForMesh(mesh)) {
  76311. return;
  76312. }
  76313. // Culling
  76314. engine.setState(material.backFaceCulling);
  76315. // Managing instances
  76316. var batch = mesh._getInstancesRenderList(subMesh._id);
  76317. if (batch.mustReturn) {
  76318. return;
  76319. }
  76320. // Excluded Mesh
  76321. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  76322. return;
  76323. }
  76324. ;
  76325. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  76326. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  76327. var emissiveTexture = null;
  76328. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  76329. emissiveTexture = material.emissiveTexture;
  76330. }
  76331. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  76332. engine.enableEffect(_this._glowMapGenerationEffect);
  76333. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  76334. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  76335. if (highlightLayerMesh) {
  76336. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  76337. }
  76338. else {
  76339. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  76340. }
  76341. // Alpha test
  76342. if (material && material.needAlphaTesting()) {
  76343. var alphaTexture = material.getAlphaTestTexture();
  76344. if (alphaTexture) {
  76345. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  76346. var textureMatrix = alphaTexture.getTextureMatrix();
  76347. if (textureMatrix) {
  76348. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  76349. }
  76350. }
  76351. }
  76352. // Glow emissive only
  76353. if (emissiveTexture) {
  76354. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  76355. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  76356. }
  76357. // Bones
  76358. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76359. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76360. }
  76361. // Draw
  76362. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  76363. }
  76364. else {
  76365. // Need to reset refresh rate of the shadowMap
  76366. _this._mainTexture.resetRefreshCounter();
  76367. }
  76368. };
  76369. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76370. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  76371. var index;
  76372. var engine = _this._scene.getEngine();
  76373. if (depthOnlySubMeshes.length) {
  76374. engine.setColorWrite(false);
  76375. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76376. renderSubMesh(depthOnlySubMeshes.data[index]);
  76377. }
  76378. engine.setColorWrite(true);
  76379. }
  76380. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76381. renderSubMesh(opaqueSubMeshes.data[index]);
  76382. }
  76383. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76384. renderSubMesh(alphaTestSubMeshes.data[index]);
  76385. }
  76386. for (index = 0; index < transparentSubMeshes.length; index++) {
  76387. renderSubMesh(transparentSubMeshes.data[index]);
  76388. }
  76389. };
  76390. this._mainTexture.onClearObservable.add(function (engine) {
  76391. engine.clear(HighlightLayer.neutralColor, true, true, true);
  76392. });
  76393. };
  76394. /**
  76395. * Checks for the readiness of the element composing the layer.
  76396. * @param subMesh the mesh to check for
  76397. * @param useInstances specify wether or not to use instances to render the mesh
  76398. * @param emissiveTexture the associated emissive texture used to generate the glow
  76399. * @return true if ready otherwise, false
  76400. */
  76401. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  76402. var material = subMesh.getMaterial();
  76403. if (!material) {
  76404. return false;
  76405. }
  76406. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  76407. return false;
  76408. }
  76409. var defines = [];
  76410. var attribs = [BABYLON.VertexBuffer.PositionKind];
  76411. var mesh = subMesh.getMesh();
  76412. var uv1 = false;
  76413. var uv2 = false;
  76414. // Alpha test
  76415. if (material && material.needAlphaTesting()) {
  76416. var alphaTexture = material.getAlphaTestTexture();
  76417. if (alphaTexture) {
  76418. defines.push("#define ALPHATEST");
  76419. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  76420. alphaTexture.coordinatesIndex === 1) {
  76421. defines.push("#define DIFFUSEUV2");
  76422. uv2 = true;
  76423. }
  76424. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76425. defines.push("#define DIFFUSEUV1");
  76426. uv1 = true;
  76427. }
  76428. }
  76429. }
  76430. // Emissive
  76431. if (emissiveTexture) {
  76432. defines.push("#define EMISSIVE");
  76433. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  76434. emissiveTexture.coordinatesIndex === 1) {
  76435. defines.push("#define EMISSIVEUV2");
  76436. uv2 = true;
  76437. }
  76438. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76439. defines.push("#define EMISSIVEUV1");
  76440. uv1 = true;
  76441. }
  76442. }
  76443. if (uv1) {
  76444. attribs.push(BABYLON.VertexBuffer.UVKind);
  76445. defines.push("#define UV1");
  76446. }
  76447. if (uv2) {
  76448. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76449. defines.push("#define UV2");
  76450. }
  76451. // Bones
  76452. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76453. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76454. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76455. if (mesh.numBoneInfluencers > 4) {
  76456. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76457. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76458. }
  76459. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76460. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  76461. }
  76462. else {
  76463. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76464. }
  76465. // Instances
  76466. if (useInstances) {
  76467. defines.push("#define INSTANCES");
  76468. attribs.push("world0");
  76469. attribs.push("world1");
  76470. attribs.push("world2");
  76471. attribs.push("world3");
  76472. }
  76473. // Get correct effect
  76474. var join = defines.join("\n");
  76475. if (this._cachedDefines !== join) {
  76476. this._cachedDefines = join;
  76477. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  76478. }
  76479. return this._glowMapGenerationEffect.isReady();
  76480. };
  76481. /**
  76482. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  76483. */
  76484. HighlightLayer.prototype.render = function () {
  76485. var currentEffect = this._glowMapMergeEffect;
  76486. // Check
  76487. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  76488. return;
  76489. var engine = this._scene.getEngine();
  76490. this.onBeforeComposeObservable.notifyObservers(this);
  76491. // Render
  76492. engine.enableEffect(currentEffect);
  76493. engine.setState(false);
  76494. // Cache
  76495. var previousStencilBuffer = engine.getStencilBuffer();
  76496. var previousStencilFunction = engine.getStencilFunction();
  76497. var previousStencilMask = engine.getStencilMask();
  76498. var previousStencilOperationPass = engine.getStencilOperationPass();
  76499. var previousStencilOperationFail = engine.getStencilOperationFail();
  76500. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  76501. var previousAlphaMode = engine.getAlphaMode();
  76502. // Texture
  76503. currentEffect.setTexture("textureSampler", this._blurTexture);
  76504. // VBOs
  76505. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  76506. // Stencil operations
  76507. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  76508. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  76509. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  76510. // Draw order
  76511. engine.setAlphaMode(this._options.alphaBlendingMode);
  76512. engine.setStencilMask(0x00);
  76513. engine.setStencilBuffer(true);
  76514. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  76515. if (this.outerGlow) {
  76516. currentEffect.setFloat("offset", 0);
  76517. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  76518. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  76519. }
  76520. if (this.innerGlow) {
  76521. currentEffect.setFloat("offset", 1);
  76522. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  76523. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  76524. }
  76525. // Restore Cache
  76526. engine.setStencilFunction(previousStencilFunction);
  76527. engine.setStencilMask(previousStencilMask);
  76528. engine.setAlphaMode(previousAlphaMode);
  76529. engine.setStencilBuffer(previousStencilBuffer);
  76530. engine.setStencilOperationPass(previousStencilOperationPass);
  76531. engine.setStencilOperationFail(previousStencilOperationFail);
  76532. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  76533. engine._stencilState.reset();
  76534. this.onAfterComposeObservable.notifyObservers(this);
  76535. // Handle size changes.
  76536. var size = this._mainTexture.getSize();
  76537. this.setMainTextureSize();
  76538. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  76539. // Recreate RTT and post processes on size change.
  76540. this.onSizeChangedObservable.notifyObservers(this);
  76541. this.disposeTextureAndPostProcesses();
  76542. this.createTextureAndPostProcesses();
  76543. }
  76544. };
  76545. /**
  76546. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  76547. * @param mesh The mesh to exclude from the highlight layer
  76548. */
  76549. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  76550. if (!this._excludedMeshes) {
  76551. return;
  76552. }
  76553. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  76554. if (!meshExcluded) {
  76555. this._excludedMeshes[mesh.uniqueId] = {
  76556. mesh: mesh,
  76557. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  76558. mesh.getEngine().setStencilBuffer(false);
  76559. }),
  76560. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  76561. mesh.getEngine().setStencilBuffer(true);
  76562. }),
  76563. };
  76564. }
  76565. };
  76566. /**
  76567. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  76568. * @param mesh The mesh to highlight
  76569. */
  76570. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  76571. if (!this._excludedMeshes) {
  76572. return;
  76573. }
  76574. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  76575. if (meshExcluded) {
  76576. if (meshExcluded.beforeRender) {
  76577. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  76578. }
  76579. if (meshExcluded.afterRender) {
  76580. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  76581. }
  76582. }
  76583. this._excludedMeshes[mesh.uniqueId] = null;
  76584. };
  76585. /**
  76586. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  76587. * @param mesh The mesh to highlight
  76588. * @param color The color of the highlight
  76589. * @param glowEmissiveOnly Extract the glow from the emissive texture
  76590. */
  76591. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  76592. var _this = this;
  76593. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  76594. if (!this._meshes) {
  76595. return;
  76596. }
  76597. var meshHighlight = this._meshes[mesh.uniqueId];
  76598. if (meshHighlight) {
  76599. meshHighlight.color = color;
  76600. }
  76601. else {
  76602. this._meshes[mesh.uniqueId] = {
  76603. mesh: mesh,
  76604. color: color,
  76605. // Lambda required for capture due to Observable this context
  76606. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  76607. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  76608. _this.defaultStencilReference(mesh);
  76609. }
  76610. else {
  76611. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  76612. }
  76613. }),
  76614. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  76615. glowEmissiveOnly: glowEmissiveOnly
  76616. };
  76617. }
  76618. this._shouldRender = true;
  76619. };
  76620. /**
  76621. * Remove a mesh from the highlight layer in order to make it stop glowing.
  76622. * @param mesh The mesh to highlight
  76623. */
  76624. HighlightLayer.prototype.removeMesh = function (mesh) {
  76625. if (!this._meshes) {
  76626. return;
  76627. }
  76628. var meshHighlight = this._meshes[mesh.uniqueId];
  76629. if (meshHighlight) {
  76630. if (meshHighlight.observerHighlight) {
  76631. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  76632. }
  76633. if (meshHighlight.observerDefault) {
  76634. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  76635. }
  76636. delete this._meshes[mesh.uniqueId];
  76637. }
  76638. this._shouldRender = false;
  76639. for (var meshHighlightToCheck in this._meshes) {
  76640. if (this._meshes[meshHighlightToCheck]) {
  76641. this._shouldRender = true;
  76642. break;
  76643. }
  76644. }
  76645. };
  76646. /**
  76647. * Returns true if the layer contains information to display, otherwise false.
  76648. */
  76649. HighlightLayer.prototype.shouldRender = function () {
  76650. return this.isEnabled && this._shouldRender;
  76651. };
  76652. /**
  76653. * Sets the main texture desired size which is the closest power of two
  76654. * of the engine canvas size.
  76655. */
  76656. HighlightLayer.prototype.setMainTextureSize = function () {
  76657. if (this._options.mainTextureFixedSize) {
  76658. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  76659. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  76660. }
  76661. else {
  76662. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  76663. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  76664. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  76665. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  76666. }
  76667. };
  76668. /**
  76669. * Force the stencil to the normal expected value for none glowing parts
  76670. */
  76671. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  76672. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  76673. };
  76674. /**
  76675. * Dispose only the render target textures and post process.
  76676. */
  76677. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  76678. this._blurTexture.dispose();
  76679. this._mainTexture.dispose();
  76680. this._downSamplePostprocess.dispose();
  76681. this._horizontalBlurPostprocess.dispose();
  76682. this._verticalBlurPostprocess.dispose();
  76683. };
  76684. /**
  76685. * Dispose the highlight layer and free resources.
  76686. */
  76687. HighlightLayer.prototype.dispose = function () {
  76688. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76689. if (vertexBuffer) {
  76690. vertexBuffer.dispose();
  76691. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  76692. }
  76693. if (this._indexBuffer) {
  76694. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  76695. this._indexBuffer = null;
  76696. }
  76697. // Clean textures and post processes
  76698. this.disposeTextureAndPostProcesses();
  76699. if (this._meshes) {
  76700. // Clean mesh references
  76701. for (var id in this._meshes) {
  76702. var meshHighlight = this._meshes[id];
  76703. if (meshHighlight && meshHighlight.mesh) {
  76704. if (meshHighlight.observerHighlight) {
  76705. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  76706. }
  76707. if (meshHighlight.observerDefault) {
  76708. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  76709. }
  76710. }
  76711. }
  76712. this._meshes = null;
  76713. }
  76714. if (this._excludedMeshes) {
  76715. for (var id in this._excludedMeshes) {
  76716. var meshHighlight = this._excludedMeshes[id];
  76717. if (meshHighlight) {
  76718. if (meshHighlight.beforeRender) {
  76719. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  76720. }
  76721. if (meshHighlight.afterRender) {
  76722. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  76723. }
  76724. }
  76725. }
  76726. this._excludedMeshes = null;
  76727. }
  76728. // Remove from scene
  76729. var index = this._scene.highlightLayers.indexOf(this, 0);
  76730. if (index > -1) {
  76731. this._scene.highlightLayers.splice(index, 1);
  76732. }
  76733. // Callback
  76734. this.onDisposeObservable.notifyObservers(this);
  76735. this.onDisposeObservable.clear();
  76736. this.onBeforeRenderMainTextureObservable.clear();
  76737. this.onBeforeBlurObservable.clear();
  76738. this.onBeforeComposeObservable.clear();
  76739. this.onAfterComposeObservable.clear();
  76740. this.onSizeChangedObservable.clear();
  76741. };
  76742. /**
  76743. * The neutral color used during the preparation of the glow effect.
  76744. * This is black by default as the blend operation is a blend operation.
  76745. */
  76746. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  76747. /**
  76748. * Stencil value used for glowing meshes.
  76749. */
  76750. HighlightLayer.glowingMeshStencilReference = 0x02;
  76751. /**
  76752. * Stencil value used for the other meshes in the scene.
  76753. */
  76754. HighlightLayer.normalMeshStencilReference = 0x01;
  76755. return HighlightLayer;
  76756. }());
  76757. BABYLON.HighlightLayer = HighlightLayer;
  76758. })(BABYLON || (BABYLON = {}));
  76759. //# sourceMappingURL=babylon.highlightlayer.js.map
  76760. var BABYLON;
  76761. (function (BABYLON) {
  76762. var AssetTaskState;
  76763. (function (AssetTaskState) {
  76764. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  76765. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  76766. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  76767. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  76768. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  76769. var AbstractAssetTask = /** @class */ (function () {
  76770. function AbstractAssetTask(name) {
  76771. this.name = name;
  76772. this.isCompleted = false;
  76773. this.taskState = AssetTaskState.INIT;
  76774. }
  76775. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  76776. var _this = this;
  76777. this.taskState = AssetTaskState.RUNNING;
  76778. this.runTask(scene, function () {
  76779. _this.onDoneCallback(onSuccess, onError);
  76780. }, function (msg, exception) {
  76781. _this.onErrorCallback(onError, msg, exception);
  76782. });
  76783. };
  76784. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  76785. throw new Error("runTask is not implemented");
  76786. };
  76787. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  76788. this.taskState = AssetTaskState.ERROR;
  76789. this.errorObject = {
  76790. message: message,
  76791. exception: exception
  76792. };
  76793. if (this.onError) {
  76794. this.onError(this, message, exception);
  76795. }
  76796. onError();
  76797. };
  76798. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  76799. try {
  76800. this.taskState = AssetTaskState.DONE;
  76801. this.isCompleted = true;
  76802. if (this.onSuccess) {
  76803. this.onSuccess(this);
  76804. }
  76805. onSuccess();
  76806. }
  76807. catch (e) {
  76808. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  76809. }
  76810. };
  76811. return AbstractAssetTask;
  76812. }());
  76813. BABYLON.AbstractAssetTask = AbstractAssetTask;
  76814. var AssetsProgressEvent = /** @class */ (function () {
  76815. function AssetsProgressEvent(remainingCount, totalCount, task) {
  76816. this.remainingCount = remainingCount;
  76817. this.totalCount = totalCount;
  76818. this.task = task;
  76819. }
  76820. return AssetsProgressEvent;
  76821. }());
  76822. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  76823. var MeshAssetTask = /** @class */ (function (_super) {
  76824. __extends(MeshAssetTask, _super);
  76825. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  76826. var _this = _super.call(this, name) || this;
  76827. _this.name = name;
  76828. _this.meshesNames = meshesNames;
  76829. _this.rootUrl = rootUrl;
  76830. _this.sceneFilename = sceneFilename;
  76831. return _this;
  76832. }
  76833. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  76834. var _this = this;
  76835. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  76836. _this.loadedMeshes = meshes;
  76837. _this.loadedParticleSystems = particleSystems;
  76838. _this.loadedSkeletons = skeletons;
  76839. onSuccess();
  76840. }, null, function (scene, message, exception) {
  76841. onError(message, exception);
  76842. });
  76843. };
  76844. return MeshAssetTask;
  76845. }(AbstractAssetTask));
  76846. BABYLON.MeshAssetTask = MeshAssetTask;
  76847. var TextFileAssetTask = /** @class */ (function (_super) {
  76848. __extends(TextFileAssetTask, _super);
  76849. function TextFileAssetTask(name, url) {
  76850. var _this = _super.call(this, name) || this;
  76851. _this.name = name;
  76852. _this.url = url;
  76853. return _this;
  76854. }
  76855. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  76856. var _this = this;
  76857. scene._loadFile(this.url, function (data) {
  76858. _this.text = data;
  76859. onSuccess();
  76860. }, undefined, false, true, function (request, exception) {
  76861. if (request) {
  76862. onError(request.status + " " + request.statusText, exception);
  76863. }
  76864. });
  76865. };
  76866. return TextFileAssetTask;
  76867. }(AbstractAssetTask));
  76868. BABYLON.TextFileAssetTask = TextFileAssetTask;
  76869. var BinaryFileAssetTask = /** @class */ (function (_super) {
  76870. __extends(BinaryFileAssetTask, _super);
  76871. function BinaryFileAssetTask(name, url) {
  76872. var _this = _super.call(this, name) || this;
  76873. _this.name = name;
  76874. _this.url = url;
  76875. return _this;
  76876. }
  76877. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  76878. var _this = this;
  76879. scene._loadFile(this.url, function (data) {
  76880. _this.data = data;
  76881. onSuccess();
  76882. }, undefined, true, true, function (request, exception) {
  76883. if (request) {
  76884. onError(request.status + " " + request.statusText, exception);
  76885. }
  76886. });
  76887. };
  76888. return BinaryFileAssetTask;
  76889. }(AbstractAssetTask));
  76890. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  76891. var ImageAssetTask = /** @class */ (function (_super) {
  76892. __extends(ImageAssetTask, _super);
  76893. function ImageAssetTask(name, url) {
  76894. var _this = _super.call(this, name) || this;
  76895. _this.name = name;
  76896. _this.url = url;
  76897. return _this;
  76898. }
  76899. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  76900. var _this = this;
  76901. var img = new Image();
  76902. BABYLON.Tools.SetCorsBehavior(this.url, img);
  76903. img.onload = function () {
  76904. _this.image = img;
  76905. onSuccess();
  76906. };
  76907. img.onerror = function (err) {
  76908. onError("Error loading image", err);
  76909. };
  76910. img.src = this.url;
  76911. };
  76912. return ImageAssetTask;
  76913. }(AbstractAssetTask));
  76914. BABYLON.ImageAssetTask = ImageAssetTask;
  76915. var TextureAssetTask = /** @class */ (function (_super) {
  76916. __extends(TextureAssetTask, _super);
  76917. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  76918. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  76919. var _this = _super.call(this, name) || this;
  76920. _this.name = name;
  76921. _this.url = url;
  76922. _this.noMipmap = noMipmap;
  76923. _this.invertY = invertY;
  76924. _this.samplingMode = samplingMode;
  76925. return _this;
  76926. }
  76927. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  76928. var onload = function () {
  76929. onSuccess();
  76930. };
  76931. var onerror = function (message, exception) {
  76932. onError(message, exception);
  76933. };
  76934. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  76935. };
  76936. return TextureAssetTask;
  76937. }(AbstractAssetTask));
  76938. BABYLON.TextureAssetTask = TextureAssetTask;
  76939. var CubeTextureAssetTask = /** @class */ (function (_super) {
  76940. __extends(CubeTextureAssetTask, _super);
  76941. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  76942. var _this = _super.call(this, name) || this;
  76943. _this.name = name;
  76944. _this.url = url;
  76945. _this.extensions = extensions;
  76946. _this.noMipmap = noMipmap;
  76947. _this.files = files;
  76948. return _this;
  76949. }
  76950. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  76951. var onload = function () {
  76952. onSuccess();
  76953. };
  76954. var onerror = function (message, exception) {
  76955. onError(message, exception);
  76956. };
  76957. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  76958. };
  76959. return CubeTextureAssetTask;
  76960. }(AbstractAssetTask));
  76961. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  76962. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  76963. __extends(HDRCubeTextureAssetTask, _super);
  76964. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  76965. if (noMipmap === void 0) { noMipmap = false; }
  76966. if (generateHarmonics === void 0) { generateHarmonics = true; }
  76967. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  76968. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  76969. var _this = _super.call(this, name) || this;
  76970. _this.name = name;
  76971. _this.url = url;
  76972. _this.size = size;
  76973. _this.noMipmap = noMipmap;
  76974. _this.generateHarmonics = generateHarmonics;
  76975. _this.useInGammaSpace = useInGammaSpace;
  76976. _this.usePMREMGenerator = usePMREMGenerator;
  76977. return _this;
  76978. }
  76979. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  76980. var onload = function () {
  76981. onSuccess();
  76982. };
  76983. var onerror = function (message, exception) {
  76984. onError(message, exception);
  76985. };
  76986. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  76987. };
  76988. return HDRCubeTextureAssetTask;
  76989. }(AbstractAssetTask));
  76990. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  76991. var AssetsManager = /** @class */ (function () {
  76992. function AssetsManager(scene) {
  76993. this._isLoading = false;
  76994. this.tasks = new Array();
  76995. this.waitingTasksCount = 0;
  76996. //Observables
  76997. this.onTaskSuccessObservable = new BABYLON.Observable();
  76998. this.onTaskErrorObservable = new BABYLON.Observable();
  76999. this.onTasksDoneObservable = new BABYLON.Observable();
  77000. this.onProgressObservable = new BABYLON.Observable();
  77001. this.useDefaultLoadingScreen = true;
  77002. this._scene = scene;
  77003. }
  77004. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  77005. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  77006. this.tasks.push(task);
  77007. return task;
  77008. };
  77009. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  77010. var task = new TextFileAssetTask(taskName, url);
  77011. this.tasks.push(task);
  77012. return task;
  77013. };
  77014. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  77015. var task = new BinaryFileAssetTask(taskName, url);
  77016. this.tasks.push(task);
  77017. return task;
  77018. };
  77019. AssetsManager.prototype.addImageTask = function (taskName, url) {
  77020. var task = new ImageAssetTask(taskName, url);
  77021. this.tasks.push(task);
  77022. return task;
  77023. };
  77024. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  77025. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  77026. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  77027. this.tasks.push(task);
  77028. return task;
  77029. };
  77030. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  77031. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  77032. this.tasks.push(task);
  77033. return task;
  77034. };
  77035. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  77036. if (noMipmap === void 0) { noMipmap = false; }
  77037. if (generateHarmonics === void 0) { generateHarmonics = true; }
  77038. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  77039. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  77040. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  77041. this.tasks.push(task);
  77042. return task;
  77043. };
  77044. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  77045. this.waitingTasksCount--;
  77046. try {
  77047. if (this.onProgress) {
  77048. this.onProgress(this.waitingTasksCount, this.tasks.length, task);
  77049. }
  77050. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this.waitingTasksCount, this.tasks.length, task));
  77051. }
  77052. catch (e) {
  77053. BABYLON.Tools.Error("Error running progress callbacks.");
  77054. console.log(e);
  77055. }
  77056. if (this.waitingTasksCount === 0) {
  77057. try {
  77058. if (this.onFinish) {
  77059. this.onFinish(this.tasks);
  77060. }
  77061. this.onTasksDoneObservable.notifyObservers(this.tasks);
  77062. }
  77063. catch (e) {
  77064. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  77065. console.log(e);
  77066. }
  77067. this._isLoading = false;
  77068. this._scene.getEngine().hideLoadingUI();
  77069. }
  77070. };
  77071. AssetsManager.prototype._runTask = function (task) {
  77072. var _this = this;
  77073. var done = function () {
  77074. try {
  77075. if (_this.onTaskSuccess) {
  77076. _this.onTaskSuccess(task);
  77077. }
  77078. _this.onTaskSuccessObservable.notifyObservers(task);
  77079. _this._decreaseWaitingTasksCount(task);
  77080. }
  77081. catch (e) {
  77082. error("Error executing task success callbacks", e);
  77083. }
  77084. };
  77085. var error = function (message, exception) {
  77086. task.errorObject = task.errorObject || {
  77087. message: message,
  77088. exception: exception
  77089. };
  77090. if (_this.onTaskError) {
  77091. _this.onTaskError(task);
  77092. }
  77093. _this.onTaskErrorObservable.notifyObservers(task);
  77094. _this._decreaseWaitingTasksCount(task);
  77095. };
  77096. task.run(this._scene, done, error);
  77097. };
  77098. AssetsManager.prototype.reset = function () {
  77099. this._isLoading = false;
  77100. this.tasks = new Array();
  77101. return this;
  77102. };
  77103. AssetsManager.prototype.load = function () {
  77104. if (this._isLoading) {
  77105. return this;
  77106. }
  77107. this._isLoading = true;
  77108. this.waitingTasksCount = this.tasks.length;
  77109. if (this.waitingTasksCount === 0) {
  77110. if (this.onFinish) {
  77111. this.onFinish(this.tasks);
  77112. }
  77113. this.onTasksDoneObservable.notifyObservers(this.tasks);
  77114. this._isLoading = false;
  77115. return this;
  77116. }
  77117. if (this.useDefaultLoadingScreen) {
  77118. this._scene.getEngine().displayLoadingUI();
  77119. }
  77120. for (var index = 0; index < this.tasks.length; index++) {
  77121. var task = this.tasks[index];
  77122. this._runTask(task);
  77123. }
  77124. return this;
  77125. };
  77126. return AssetsManager;
  77127. }());
  77128. BABYLON.AssetsManager = AssetsManager;
  77129. })(BABYLON || (BABYLON = {}));
  77130. //# sourceMappingURL=babylon.assetsManager.js.map
  77131. var BABYLON;
  77132. (function (BABYLON) {
  77133. var serializedGeometries = [];
  77134. var serializeGeometry = function (geometry, serializationGeometries) {
  77135. if (serializedGeometries[geometry.id]) {
  77136. return;
  77137. }
  77138. if (geometry.doNotSerialize) {
  77139. return;
  77140. }
  77141. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  77142. serializationGeometries.boxes.push(geometry.serialize());
  77143. }
  77144. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  77145. serializationGeometries.spheres.push(geometry.serialize());
  77146. }
  77147. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  77148. serializationGeometries.cylinders.push(geometry.serialize());
  77149. }
  77150. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  77151. serializationGeometries.toruses.push(geometry.serialize());
  77152. }
  77153. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  77154. serializationGeometries.grounds.push(geometry.serialize());
  77155. }
  77156. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  77157. serializationGeometries.planes.push(geometry.serialize());
  77158. }
  77159. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  77160. serializationGeometries.torusKnots.push(geometry.serialize());
  77161. }
  77162. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  77163. throw new Error("Unknown primitive type");
  77164. }
  77165. else {
  77166. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  77167. }
  77168. serializedGeometries[geometry.id] = true;
  77169. };
  77170. var serializeMesh = function (mesh, serializationScene) {
  77171. var serializationObject = {};
  77172. // Geometry
  77173. var geometry = mesh._geometry;
  77174. if (geometry) {
  77175. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  77176. // 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
  77177. serializeGeometry(geometry, serializationScene.geometries);
  77178. }
  77179. }
  77180. // Custom
  77181. if (mesh.serialize) {
  77182. mesh.serialize(serializationObject);
  77183. }
  77184. return serializationObject;
  77185. };
  77186. var finalizeSingleMesh = function (mesh, serializationObject) {
  77187. //only works if the mesh is already loaded
  77188. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  77189. //serialize material
  77190. if (mesh.material) {
  77191. if (mesh.material instanceof BABYLON.StandardMaterial) {
  77192. serializationObject.materials = serializationObject.materials || [];
  77193. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  77194. serializationObject.materials.push(mesh.material.serialize());
  77195. }
  77196. }
  77197. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  77198. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  77199. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  77200. serializationObject.multiMaterials.push(mesh.material.serialize());
  77201. }
  77202. }
  77203. }
  77204. //serialize geometry
  77205. var geometry = mesh._geometry;
  77206. if (geometry) {
  77207. if (!serializationObject.geometries) {
  77208. serializationObject.geometries = {};
  77209. serializationObject.geometries.boxes = [];
  77210. serializationObject.geometries.spheres = [];
  77211. serializationObject.geometries.cylinders = [];
  77212. serializationObject.geometries.toruses = [];
  77213. serializationObject.geometries.grounds = [];
  77214. serializationObject.geometries.planes = [];
  77215. serializationObject.geometries.torusKnots = [];
  77216. serializationObject.geometries.vertexData = [];
  77217. }
  77218. serializeGeometry(geometry, serializationObject.geometries);
  77219. }
  77220. // Skeletons
  77221. if (mesh.skeleton) {
  77222. serializationObject.skeletons = serializationObject.skeletons || [];
  77223. serializationObject.skeletons.push(mesh.skeleton.serialize());
  77224. }
  77225. //serialize the actual mesh
  77226. serializationObject.meshes = serializationObject.meshes || [];
  77227. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  77228. }
  77229. };
  77230. var SceneSerializer = /** @class */ (function () {
  77231. function SceneSerializer() {
  77232. }
  77233. SceneSerializer.ClearCache = function () {
  77234. serializedGeometries = [];
  77235. };
  77236. SceneSerializer.Serialize = function (scene) {
  77237. var serializationObject = {};
  77238. SceneSerializer.ClearCache();
  77239. // Scene
  77240. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  77241. serializationObject.autoClear = scene.autoClear;
  77242. serializationObject.clearColor = scene.clearColor.asArray();
  77243. serializationObject.ambientColor = scene.ambientColor.asArray();
  77244. serializationObject.gravity = scene.gravity.asArray();
  77245. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  77246. serializationObject.workerCollisions = scene.workerCollisions;
  77247. // Fog
  77248. if (scene.fogMode && scene.fogMode !== 0) {
  77249. serializationObject.fogMode = scene.fogMode;
  77250. serializationObject.fogColor = scene.fogColor.asArray();
  77251. serializationObject.fogStart = scene.fogStart;
  77252. serializationObject.fogEnd = scene.fogEnd;
  77253. serializationObject.fogDensity = scene.fogDensity;
  77254. }
  77255. //Physics
  77256. if (scene.isPhysicsEnabled()) {
  77257. var physicEngine = scene.getPhysicsEngine();
  77258. if (physicEngine) {
  77259. serializationObject.physicsEnabled = true;
  77260. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  77261. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  77262. }
  77263. }
  77264. // Metadata
  77265. if (scene.metadata) {
  77266. serializationObject.metadata = scene.metadata;
  77267. }
  77268. // Morph targets
  77269. serializationObject.morphTargetManagers = [];
  77270. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  77271. var abstractMesh = _a[_i];
  77272. var manager = abstractMesh.morphTargetManager;
  77273. if (manager) {
  77274. serializationObject.morphTargetManagers.push(manager.serialize());
  77275. }
  77276. }
  77277. // Lights
  77278. serializationObject.lights = [];
  77279. var index;
  77280. var light;
  77281. for (index = 0; index < scene.lights.length; index++) {
  77282. light = scene.lights[index];
  77283. if (!light.doNotSerialize) {
  77284. serializationObject.lights.push(light.serialize());
  77285. }
  77286. }
  77287. // Cameras
  77288. serializationObject.cameras = [];
  77289. for (index = 0; index < scene.cameras.length; index++) {
  77290. var camera = scene.cameras[index];
  77291. if (!camera.doNotSerialize) {
  77292. serializationObject.cameras.push(camera.serialize());
  77293. }
  77294. }
  77295. if (scene.activeCamera) {
  77296. serializationObject.activeCameraID = scene.activeCamera.id;
  77297. }
  77298. // Animations
  77299. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  77300. // Materials
  77301. serializationObject.materials = [];
  77302. serializationObject.multiMaterials = [];
  77303. var material;
  77304. for (index = 0; index < scene.materials.length; index++) {
  77305. material = scene.materials[index];
  77306. if (!material.doNotSerialize) {
  77307. serializationObject.materials.push(material.serialize());
  77308. }
  77309. }
  77310. // MultiMaterials
  77311. serializationObject.multiMaterials = [];
  77312. for (index = 0; index < scene.multiMaterials.length; index++) {
  77313. var multiMaterial = scene.multiMaterials[index];
  77314. serializationObject.multiMaterials.push(multiMaterial.serialize());
  77315. }
  77316. // Environment texture
  77317. if (scene.environmentTexture) {
  77318. serializationObject.environmentTexture = scene.environmentTexture.name;
  77319. }
  77320. // Skeletons
  77321. serializationObject.skeletons = [];
  77322. for (index = 0; index < scene.skeletons.length; index++) {
  77323. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  77324. }
  77325. // Transform nodes
  77326. serializationObject.transformNodes = [];
  77327. for (index = 0; index < scene.transformNodes.length; index++) {
  77328. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  77329. }
  77330. // Geometries
  77331. serializationObject.geometries = {};
  77332. serializationObject.geometries.boxes = [];
  77333. serializationObject.geometries.spheres = [];
  77334. serializationObject.geometries.cylinders = [];
  77335. serializationObject.geometries.toruses = [];
  77336. serializationObject.geometries.grounds = [];
  77337. serializationObject.geometries.planes = [];
  77338. serializationObject.geometries.torusKnots = [];
  77339. serializationObject.geometries.vertexData = [];
  77340. serializedGeometries = [];
  77341. var geometries = scene.getGeometries();
  77342. for (index = 0; index < geometries.length; index++) {
  77343. var geometry = geometries[index];
  77344. if (geometry.isReady()) {
  77345. serializeGeometry(geometry, serializationObject.geometries);
  77346. }
  77347. }
  77348. // Meshes
  77349. serializationObject.meshes = [];
  77350. for (index = 0; index < scene.meshes.length; index++) {
  77351. var abstractMesh = scene.meshes[index];
  77352. if (abstractMesh instanceof BABYLON.Mesh) {
  77353. var mesh = abstractMesh;
  77354. if (!mesh.doNotSerialize) {
  77355. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  77356. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  77357. }
  77358. }
  77359. }
  77360. }
  77361. // Particles Systems
  77362. serializationObject.particleSystems = [];
  77363. for (index = 0; index < scene.particleSystems.length; index++) {
  77364. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  77365. }
  77366. // Lens flares
  77367. serializationObject.lensFlareSystems = [];
  77368. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  77369. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  77370. }
  77371. // Shadows
  77372. serializationObject.shadowGenerators = [];
  77373. for (index = 0; index < scene.lights.length; index++) {
  77374. light = scene.lights[index];
  77375. var shadowGenerator = light.getShadowGenerator();
  77376. if (shadowGenerator) {
  77377. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  77378. }
  77379. }
  77380. // Action Manager
  77381. if (scene.actionManager) {
  77382. serializationObject.actions = scene.actionManager.serialize("scene");
  77383. }
  77384. // Audio
  77385. serializationObject.sounds = [];
  77386. for (index = 0; index < scene.soundTracks.length; index++) {
  77387. var soundtrack = scene.soundTracks[index];
  77388. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  77389. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  77390. }
  77391. }
  77392. return serializationObject;
  77393. };
  77394. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  77395. if (withParents === void 0) { withParents = false; }
  77396. if (withChildren === void 0) { withChildren = false; }
  77397. var serializationObject = {};
  77398. SceneSerializer.ClearCache();
  77399. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  77400. if (withParents || withChildren) {
  77401. //deliberate for loop! not for each, appended should be processed as well.
  77402. for (var i = 0; i < toSerialize.length; ++i) {
  77403. if (withChildren) {
  77404. toSerialize[i].getDescendants().forEach(function (node) {
  77405. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  77406. toSerialize.push(node);
  77407. }
  77408. });
  77409. }
  77410. //make sure the array doesn't contain the object already
  77411. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  77412. toSerialize.push(toSerialize[i].parent);
  77413. }
  77414. }
  77415. }
  77416. toSerialize.forEach(function (mesh) {
  77417. finalizeSingleMesh(mesh, serializationObject);
  77418. });
  77419. return serializationObject;
  77420. };
  77421. return SceneSerializer;
  77422. }());
  77423. BABYLON.SceneSerializer = SceneSerializer;
  77424. })(BABYLON || (BABYLON = {}));
  77425. //# sourceMappingURL=babylon.sceneSerializer.js.map
  77426. var BABYLON;
  77427. (function (BABYLON) {
  77428. var ReflectionProbe = /** @class */ (function () {
  77429. function ReflectionProbe(name, size, scene, generateMipMaps) {
  77430. if (generateMipMaps === void 0) { generateMipMaps = true; }
  77431. var _this = this;
  77432. this.name = name;
  77433. this._viewMatrix = BABYLON.Matrix.Identity();
  77434. this._target = BABYLON.Vector3.Zero();
  77435. this._add = BABYLON.Vector3.Zero();
  77436. this.invertYAxis = false;
  77437. this.position = BABYLON.Vector3.Zero();
  77438. this._scene = scene;
  77439. this._scene.reflectionProbes.push(this);
  77440. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  77441. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  77442. switch (faceIndex) {
  77443. case 0:
  77444. _this._add.copyFromFloats(1, 0, 0);
  77445. break;
  77446. case 1:
  77447. _this._add.copyFromFloats(-1, 0, 0);
  77448. break;
  77449. case 2:
  77450. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  77451. break;
  77452. case 3:
  77453. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  77454. break;
  77455. case 4:
  77456. _this._add.copyFromFloats(0, 0, 1);
  77457. break;
  77458. case 5:
  77459. _this._add.copyFromFloats(0, 0, -1);
  77460. break;
  77461. }
  77462. if (_this._attachedMesh) {
  77463. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  77464. }
  77465. _this.position.addToRef(_this._add, _this._target);
  77466. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  77467. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  77468. scene._forcedViewPosition = _this.position;
  77469. });
  77470. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  77471. scene._forcedViewPosition = null;
  77472. scene.updateTransformMatrix(true);
  77473. });
  77474. if (scene.activeCamera) {
  77475. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  77476. }
  77477. }
  77478. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  77479. get: function () {
  77480. return this._renderTargetTexture.samples;
  77481. },
  77482. set: function (value) {
  77483. this._renderTargetTexture.samples = value;
  77484. },
  77485. enumerable: true,
  77486. configurable: true
  77487. });
  77488. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  77489. get: function () {
  77490. return this._renderTargetTexture.refreshRate;
  77491. },
  77492. set: function (value) {
  77493. this._renderTargetTexture.refreshRate = value;
  77494. },
  77495. enumerable: true,
  77496. configurable: true
  77497. });
  77498. ReflectionProbe.prototype.getScene = function () {
  77499. return this._scene;
  77500. };
  77501. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  77502. get: function () {
  77503. return this._renderTargetTexture;
  77504. },
  77505. enumerable: true,
  77506. configurable: true
  77507. });
  77508. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  77509. get: function () {
  77510. return this._renderTargetTexture.renderList;
  77511. },
  77512. enumerable: true,
  77513. configurable: true
  77514. });
  77515. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  77516. this._attachedMesh = mesh;
  77517. };
  77518. /**
  77519. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  77520. *
  77521. * @param renderingGroupId The rendering group id corresponding to its index
  77522. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  77523. */
  77524. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  77525. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  77526. };
  77527. ReflectionProbe.prototype.dispose = function () {
  77528. var index = this._scene.reflectionProbes.indexOf(this);
  77529. if (index !== -1) {
  77530. // Remove from the scene if found
  77531. this._scene.reflectionProbes.splice(index, 1);
  77532. }
  77533. if (this._renderTargetTexture) {
  77534. this._renderTargetTexture.dispose();
  77535. this._renderTargetTexture = null;
  77536. }
  77537. };
  77538. return ReflectionProbe;
  77539. }());
  77540. BABYLON.ReflectionProbe = ReflectionProbe;
  77541. })(BABYLON || (BABYLON = {}));
  77542. //# sourceMappingURL=babylon.reflectionProbe.js.map
  77543. var BABYLON;
  77544. (function (BABYLON) {
  77545. var Layer = /** @class */ (function () {
  77546. function Layer(name, imgUrl, scene, isBackground, color) {
  77547. this.name = name;
  77548. this.scale = new BABYLON.Vector2(1, 1);
  77549. this.offset = new BABYLON.Vector2(0, 0);
  77550. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  77551. this.layerMask = 0x0FFFFFFF;
  77552. this._vertexBuffers = {};
  77553. // Events
  77554. /**
  77555. * An event triggered when the layer is disposed.
  77556. * @type {BABYLON.Observable}
  77557. */
  77558. this.onDisposeObservable = new BABYLON.Observable();
  77559. /**
  77560. * An event triggered before rendering the scene
  77561. * @type {BABYLON.Observable}
  77562. */
  77563. this.onBeforeRenderObservable = new BABYLON.Observable();
  77564. /**
  77565. * An event triggered after rendering the scene
  77566. * @type {BABYLON.Observable}
  77567. */
  77568. this.onAfterRenderObservable = new BABYLON.Observable();
  77569. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  77570. this.isBackground = isBackground === undefined ? true : isBackground;
  77571. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  77572. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  77573. this._scene.layers.push(this);
  77574. var engine = this._scene.getEngine();
  77575. // VBO
  77576. var vertices = [];
  77577. vertices.push(1, 1);
  77578. vertices.push(-1, 1);
  77579. vertices.push(-1, -1);
  77580. vertices.push(1, -1);
  77581. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  77582. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  77583. this._createIndexBuffer();
  77584. // Effects
  77585. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  77586. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  77587. }
  77588. Object.defineProperty(Layer.prototype, "onDispose", {
  77589. set: function (callback) {
  77590. if (this._onDisposeObserver) {
  77591. this.onDisposeObservable.remove(this._onDisposeObserver);
  77592. }
  77593. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  77594. },
  77595. enumerable: true,
  77596. configurable: true
  77597. });
  77598. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  77599. set: function (callback) {
  77600. if (this._onBeforeRenderObserver) {
  77601. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  77602. }
  77603. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  77604. },
  77605. enumerable: true,
  77606. configurable: true
  77607. });
  77608. Object.defineProperty(Layer.prototype, "onAfterRender", {
  77609. set: function (callback) {
  77610. if (this._onAfterRenderObserver) {
  77611. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  77612. }
  77613. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  77614. },
  77615. enumerable: true,
  77616. configurable: true
  77617. });
  77618. Layer.prototype._createIndexBuffer = function () {
  77619. var engine = this._scene.getEngine();
  77620. // Indices
  77621. var indices = [];
  77622. indices.push(0);
  77623. indices.push(1);
  77624. indices.push(2);
  77625. indices.push(0);
  77626. indices.push(2);
  77627. indices.push(3);
  77628. this._indexBuffer = engine.createIndexBuffer(indices);
  77629. };
  77630. Layer.prototype._rebuild = function () {
  77631. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  77632. if (vb) {
  77633. vb._rebuild();
  77634. }
  77635. this._createIndexBuffer();
  77636. };
  77637. Layer.prototype.render = function () {
  77638. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  77639. // Check
  77640. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  77641. return;
  77642. var engine = this._scene.getEngine();
  77643. this.onBeforeRenderObservable.notifyObservers(this);
  77644. // Render
  77645. engine.enableEffect(currentEffect);
  77646. engine.setState(false);
  77647. // Texture
  77648. currentEffect.setTexture("textureSampler", this.texture);
  77649. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  77650. // Color
  77651. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  77652. // Scale / offset
  77653. currentEffect.setVector2("offset", this.offset);
  77654. currentEffect.setVector2("scale", this.scale);
  77655. // VBOs
  77656. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  77657. // Draw order
  77658. if (!this.alphaTest) {
  77659. engine.setAlphaMode(this.alphaBlendingMode);
  77660. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  77661. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  77662. }
  77663. else {
  77664. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  77665. }
  77666. this.onAfterRenderObservable.notifyObservers(this);
  77667. };
  77668. Layer.prototype.dispose = function () {
  77669. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  77670. if (vertexBuffer) {
  77671. vertexBuffer.dispose();
  77672. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  77673. }
  77674. if (this._indexBuffer) {
  77675. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  77676. this._indexBuffer = null;
  77677. }
  77678. if (this.texture) {
  77679. this.texture.dispose();
  77680. this.texture = null;
  77681. }
  77682. // Remove from scene
  77683. var index = this._scene.layers.indexOf(this);
  77684. this._scene.layers.splice(index, 1);
  77685. // Callback
  77686. this.onDisposeObservable.notifyObservers(this);
  77687. this.onDisposeObservable.clear();
  77688. this.onAfterRenderObservable.clear();
  77689. this.onBeforeRenderObservable.clear();
  77690. };
  77691. return Layer;
  77692. }());
  77693. BABYLON.Layer = Layer;
  77694. })(BABYLON || (BABYLON = {}));
  77695. //# sourceMappingURL=babylon.layer.js.map
  77696. var BABYLON;
  77697. (function (BABYLON) {
  77698. var TextureTools = /** @class */ (function () {
  77699. function TextureTools() {
  77700. }
  77701. /**
  77702. * Uses the GPU to create a copy texture rescaled at a given size
  77703. * @param texture Texture to copy from
  77704. * @param width Desired width
  77705. * @param height Desired height
  77706. * @return Generated texture
  77707. */
  77708. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  77709. if (useBilinearMode === void 0) { useBilinearMode = true; }
  77710. var scene = texture.getScene();
  77711. var engine = scene.getEngine();
  77712. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  77713. rtt.wrapU = texture.wrapU;
  77714. rtt.wrapV = texture.wrapV;
  77715. rtt.uOffset = texture.uOffset;
  77716. rtt.vOffset = texture.vOffset;
  77717. rtt.uScale = texture.uScale;
  77718. rtt.vScale = texture.vScale;
  77719. rtt.uAng = texture.uAng;
  77720. rtt.vAng = texture.vAng;
  77721. rtt.wAng = texture.wAng;
  77722. rtt.coordinatesIndex = texture.coordinatesIndex;
  77723. rtt.level = texture.level;
  77724. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  77725. rtt._texture.isReady = false;
  77726. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77727. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77728. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  77729. passPostProcess.getEffect().executeWhenCompiled(function () {
  77730. passPostProcess.onApply = function (effect) {
  77731. effect.setTexture("textureSampler", texture);
  77732. };
  77733. var internalTexture = rtt.getInternalTexture();
  77734. if (internalTexture) {
  77735. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  77736. engine.unBindFramebuffer(internalTexture);
  77737. rtt.disposeFramebufferObjects();
  77738. passPostProcess.dispose();
  77739. internalTexture.isReady = true;
  77740. }
  77741. });
  77742. return rtt;
  77743. };
  77744. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  77745. if (!scene._environmentBRDFTexture) {
  77746. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77747. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77748. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77749. scene._environmentBRDFTexture = texture;
  77750. }
  77751. return scene._environmentBRDFTexture;
  77752. };
  77753. 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=";
  77754. return TextureTools;
  77755. }());
  77756. BABYLON.TextureTools = TextureTools;
  77757. })(BABYLON || (BABYLON = {}));
  77758. //# sourceMappingURL=babylon.textureTools.js.map
  77759. var BABYLON;
  77760. (function (BABYLON) {
  77761. var FramingBehavior = /** @class */ (function () {
  77762. function FramingBehavior() {
  77763. this._mode = FramingBehavior.FitFrustumSidesMode;
  77764. this._radiusScale = 1.0;
  77765. this._positionScale = 0.5;
  77766. this._defaultElevation = 0.3;
  77767. this._elevationReturnTime = 1500;
  77768. this._elevationReturnWaitTime = 1000;
  77769. this._zoomStopsAnimation = false;
  77770. this._framingTime = 1500;
  77771. this._isPointerDown = false;
  77772. this._lastInteractionTime = -Infinity;
  77773. // Framing control
  77774. this._animatables = new Array();
  77775. this._betaIsAnimating = false;
  77776. }
  77777. Object.defineProperty(FramingBehavior.prototype, "name", {
  77778. get: function () {
  77779. return "Framing";
  77780. },
  77781. enumerable: true,
  77782. configurable: true
  77783. });
  77784. Object.defineProperty(FramingBehavior.prototype, "mode", {
  77785. /**
  77786. * Gets current mode used by the behavior.
  77787. */
  77788. get: function () {
  77789. return this._mode;
  77790. },
  77791. /**
  77792. * Sets the current mode used by the behavior
  77793. */
  77794. set: function (mode) {
  77795. this._mode = mode;
  77796. },
  77797. enumerable: true,
  77798. configurable: true
  77799. });
  77800. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  77801. /**
  77802. * Gets the scale applied to the radius
  77803. */
  77804. get: function () {
  77805. return this._radiusScale;
  77806. },
  77807. /**
  77808. * Sets the scale applied to the radius (1 by default)
  77809. */
  77810. set: function (radius) {
  77811. this._radiusScale = radius;
  77812. },
  77813. enumerable: true,
  77814. configurable: true
  77815. });
  77816. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  77817. /**
  77818. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  77819. */
  77820. get: function () {
  77821. return this._positionScale;
  77822. },
  77823. /**
  77824. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  77825. */
  77826. set: function (scale) {
  77827. this._positionScale = scale;
  77828. },
  77829. enumerable: true,
  77830. configurable: true
  77831. });
  77832. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  77833. /**
  77834. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  77835. * behaviour is triggered, in radians.
  77836. */
  77837. get: function () {
  77838. return this._defaultElevation;
  77839. },
  77840. /**
  77841. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  77842. * behaviour is triggered, in radians.
  77843. */
  77844. set: function (elevation) {
  77845. this._defaultElevation = elevation;
  77846. },
  77847. enumerable: true,
  77848. configurable: true
  77849. });
  77850. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  77851. /**
  77852. * Gets the time (in milliseconds) taken to return to the default beta position.
  77853. * Negative value indicates camera should not return to default.
  77854. */
  77855. get: function () {
  77856. return this._elevationReturnTime;
  77857. },
  77858. /**
  77859. * Sets the time (in milliseconds) taken to return to the default beta position.
  77860. * Negative value indicates camera should not return to default.
  77861. */
  77862. set: function (speed) {
  77863. this._elevationReturnTime = speed;
  77864. },
  77865. enumerable: true,
  77866. configurable: true
  77867. });
  77868. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  77869. /**
  77870. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  77871. */
  77872. get: function () {
  77873. return this._elevationReturnWaitTime;
  77874. },
  77875. /**
  77876. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  77877. */
  77878. set: function (time) {
  77879. this._elevationReturnWaitTime = time;
  77880. },
  77881. enumerable: true,
  77882. configurable: true
  77883. });
  77884. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  77885. /**
  77886. * Gets the flag that indicates if user zooming should stop animation.
  77887. */
  77888. get: function () {
  77889. return this._zoomStopsAnimation;
  77890. },
  77891. /**
  77892. * Sets the flag that indicates if user zooming should stop animation.
  77893. */
  77894. set: function (flag) {
  77895. this._zoomStopsAnimation = flag;
  77896. },
  77897. enumerable: true,
  77898. configurable: true
  77899. });
  77900. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  77901. /**
  77902. * Gets the transition time when framing the mesh, in milliseconds
  77903. */
  77904. get: function () {
  77905. return this._framingTime;
  77906. },
  77907. /**
  77908. * Sets the transition time when framing the mesh, in milliseconds
  77909. */
  77910. set: function (time) {
  77911. this._framingTime = time;
  77912. },
  77913. enumerable: true,
  77914. configurable: true
  77915. });
  77916. FramingBehavior.prototype.init = function () {
  77917. // Do notihng
  77918. };
  77919. FramingBehavior.prototype.attach = function (camera) {
  77920. var _this = this;
  77921. this._attachedCamera = camera;
  77922. var scene = this._attachedCamera.getScene();
  77923. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  77924. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  77925. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  77926. _this._isPointerDown = true;
  77927. return;
  77928. }
  77929. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  77930. _this._isPointerDown = false;
  77931. }
  77932. });
  77933. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  77934. if (mesh) {
  77935. _this.zoomOnMesh(mesh);
  77936. }
  77937. });
  77938. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  77939. // Stop the animation if there is user interaction and the animation should stop for this interaction
  77940. _this._applyUserInteraction();
  77941. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  77942. // back to the default position after a given timeout
  77943. _this._maintainCameraAboveGround();
  77944. });
  77945. };
  77946. FramingBehavior.prototype.detach = function () {
  77947. if (!this._attachedCamera) {
  77948. return;
  77949. }
  77950. var scene = this._attachedCamera.getScene();
  77951. if (this._onPrePointerObservableObserver) {
  77952. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  77953. }
  77954. if (this._onAfterCheckInputsObserver) {
  77955. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  77956. }
  77957. if (this._onMeshTargetChangedObserver) {
  77958. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  77959. }
  77960. this._attachedCamera = null;
  77961. };
  77962. /**
  77963. * Targets the given mesh and updates zoom level accordingly.
  77964. * @param mesh The mesh to target.
  77965. * @param radius Optional. If a cached radius position already exists, overrides default.
  77966. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  77967. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  77968. * @param onAnimationEnd Callback triggered at the end of the framing animation
  77969. */
  77970. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  77971. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  77972. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  77973. mesh.computeWorldMatrix(true);
  77974. var boundingBox = mesh.getBoundingInfo().boundingBox;
  77975. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  77976. };
  77977. /**
  77978. * Targets the given mesh with its children and updates zoom level accordingly.
  77979. * @param mesh The mesh to target.
  77980. * @param radius Optional. If a cached radius position already exists, overrides default.
  77981. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  77982. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  77983. * @param onAnimationEnd Callback triggered at the end of the framing animation
  77984. */
  77985. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  77986. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  77987. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  77988. mesh.computeWorldMatrix(true);
  77989. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  77990. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  77991. };
  77992. /**
  77993. * Targets the given meshes with their children and updates zoom level accordingly.
  77994. * @param meshes The mesh to target.
  77995. * @param radius Optional. If a cached radius position already exists, overrides default.
  77996. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  77997. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  77998. * @param onAnimationEnd Callback triggered at the end of the framing animation
  77999. */
  78000. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  78001. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  78002. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  78003. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  78004. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  78005. for (var i = 0; i < meshes.length; i++) {
  78006. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  78007. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  78008. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  78009. }
  78010. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  78011. };
  78012. /**
  78013. * Targets the given mesh and updates zoom level accordingly.
  78014. * @param mesh The mesh to target.
  78015. * @param radius Optional. If a cached radius position already exists, overrides default.
  78016. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  78017. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  78018. * @param onAnimationEnd Callback triggered at the end of the framing animation
  78019. */
  78020. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  78021. var _this = this;
  78022. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  78023. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  78024. var zoomTarget;
  78025. if (!this._attachedCamera) {
  78026. return;
  78027. }
  78028. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  78029. var bottom = minimumWorld.y;
  78030. var top = maximumWorld.y;
  78031. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  78032. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  78033. if (focusOnOriginXZ) {
  78034. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  78035. }
  78036. else {
  78037. var centerWorld = minimumWorld.add(radiusWorld);
  78038. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  78039. }
  78040. if (!this._vectorTransition) {
  78041. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  78042. }
  78043. this._betaIsAnimating = true;
  78044. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  78045. if (animatable) {
  78046. this._animatables.push(animatable);
  78047. }
  78048. // sets the radius and lower radius bounds
  78049. // Small delta ensures camera is not always at lower zoom limit.
  78050. var radius = 0;
  78051. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  78052. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  78053. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  78054. radius = position;
  78055. }
  78056. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  78057. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  78058. if (this._attachedCamera.lowerRadiusLimit === null) {
  78059. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  78060. }
  78061. }
  78062. // Set sensibilities
  78063. var extend = maximumWorld.subtract(minimumWorld).length();
  78064. this._attachedCamera.panningSensibility = 5000 / extend;
  78065. this._attachedCamera.wheelPrecision = 100 / radius;
  78066. // transition to new radius
  78067. if (!this._radiusTransition) {
  78068. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  78069. }
  78070. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  78071. if (onAnimationEnd) {
  78072. onAnimationEnd();
  78073. }
  78074. if (_this._attachedCamera) {
  78075. _this._attachedCamera.storeState();
  78076. }
  78077. });
  78078. if (animatable) {
  78079. this._animatables.push(animatable);
  78080. }
  78081. };
  78082. /**
  78083. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  78084. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  78085. * frustum width.
  78086. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  78087. * to fully enclose the mesh in the viewing frustum.
  78088. */
  78089. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  78090. var size = maximumWorld.subtract(minimumWorld);
  78091. var boxVectorGlobalDiagonal = size.length();
  78092. var frustumSlope = this._getFrustumSlope();
  78093. // Formula for setting distance
  78094. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  78095. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  78096. // Horizon distance
  78097. var radius = radiusWithoutFraming * this._radiusScale;
  78098. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  78099. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  78100. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  78101. var camera = this._attachedCamera;
  78102. if (!camera) {
  78103. return 0;
  78104. }
  78105. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  78106. // Don't exceed the requested limit
  78107. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  78108. }
  78109. // Don't exceed the upper radius limit
  78110. if (camera.upperRadiusLimit) {
  78111. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  78112. }
  78113. return distance;
  78114. };
  78115. /**
  78116. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  78117. * is automatically returned to its default position (expected to be above ground plane).
  78118. */
  78119. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  78120. var _this = this;
  78121. if (this._elevationReturnTime < 0) {
  78122. return;
  78123. }
  78124. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  78125. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  78126. var limitBeta = Math.PI * 0.5;
  78127. // Bring the camera back up if below the ground plane
  78128. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  78129. this._betaIsAnimating = true;
  78130. //Transition to new position
  78131. this.stopAllAnimations();
  78132. if (!this._betaTransition) {
  78133. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  78134. }
  78135. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  78136. _this._clearAnimationLocks();
  78137. _this.stopAllAnimations();
  78138. });
  78139. if (animatabe) {
  78140. this._animatables.push(animatabe);
  78141. }
  78142. }
  78143. };
  78144. /**
  78145. * Returns the frustum slope based on the canvas ratio and camera FOV
  78146. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  78147. */
  78148. FramingBehavior.prototype._getFrustumSlope = function () {
  78149. // Calculate the viewport ratio
  78150. // Aspect Ratio is Height/Width.
  78151. var camera = this._attachedCamera;
  78152. if (!camera) {
  78153. return BABYLON.Vector2.Zero();
  78154. }
  78155. var engine = camera.getScene().getEngine();
  78156. var aspectRatio = engine.getAspectRatio(camera);
  78157. // Camera FOV is the vertical field of view (top-bottom) in radians.
  78158. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  78159. var frustumSlopeY = Math.tan(camera.fov / 2);
  78160. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  78161. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  78162. // along the forward vector.
  78163. var frustumSlopeX = frustumSlopeY * aspectRatio;
  78164. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  78165. };
  78166. /**
  78167. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  78168. */
  78169. FramingBehavior.prototype._clearAnimationLocks = function () {
  78170. this._betaIsAnimating = false;
  78171. };
  78172. /**
  78173. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  78174. */
  78175. FramingBehavior.prototype._applyUserInteraction = function () {
  78176. if (this.isUserIsMoving) {
  78177. this._lastInteractionTime = BABYLON.Tools.Now;
  78178. this.stopAllAnimations();
  78179. this._clearAnimationLocks();
  78180. }
  78181. };
  78182. /**
  78183. * Stops and removes all animations that have been applied to the camera
  78184. */
  78185. FramingBehavior.prototype.stopAllAnimations = function () {
  78186. if (this._attachedCamera) {
  78187. this._attachedCamera.animations = [];
  78188. }
  78189. while (this._animatables.length) {
  78190. if (this._animatables[0]) {
  78191. this._animatables[0].onAnimationEnd = null;
  78192. this._animatables[0].stop();
  78193. }
  78194. this._animatables.shift();
  78195. }
  78196. };
  78197. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  78198. /**
  78199. * Gets a value indicating if the user is moving the camera
  78200. */
  78201. get: function () {
  78202. if (!this._attachedCamera) {
  78203. return false;
  78204. }
  78205. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  78206. this._attachedCamera.inertialBetaOffset !== 0 ||
  78207. this._attachedCamera.inertialRadiusOffset !== 0 ||
  78208. this._attachedCamera.inertialPanningX !== 0 ||
  78209. this._attachedCamera.inertialPanningY !== 0 ||
  78210. this._isPointerDown;
  78211. },
  78212. enumerable: true,
  78213. configurable: true
  78214. });
  78215. /**
  78216. * The easing function used by animations
  78217. */
  78218. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  78219. /**
  78220. * The easing mode used by animations
  78221. */
  78222. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  78223. // Statics
  78224. /**
  78225. * The camera can move all the way towards the mesh.
  78226. */
  78227. FramingBehavior.IgnoreBoundsSizeMode = 0;
  78228. /**
  78229. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  78230. */
  78231. FramingBehavior.FitFrustumSidesMode = 1;
  78232. return FramingBehavior;
  78233. }());
  78234. BABYLON.FramingBehavior = FramingBehavior;
  78235. })(BABYLON || (BABYLON = {}));
  78236. //# sourceMappingURL=babylon.framingBehavior.js.map
  78237. var BABYLON;
  78238. (function (BABYLON) {
  78239. /**
  78240. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  78241. */
  78242. var BouncingBehavior = /** @class */ (function () {
  78243. function BouncingBehavior() {
  78244. /**
  78245. * The duration of the animation, in milliseconds
  78246. */
  78247. this.transitionDuration = 450;
  78248. /**
  78249. * Length of the distance animated by the transition when lower radius is reached
  78250. */
  78251. this.lowerRadiusTransitionRange = 2;
  78252. /**
  78253. * Length of the distance animated by the transition when upper radius is reached
  78254. */
  78255. this.upperRadiusTransitionRange = -2;
  78256. this._autoTransitionRange = false;
  78257. // Animations
  78258. this._radiusIsAnimating = false;
  78259. this._radiusBounceTransition = null;
  78260. this._animatables = new Array();
  78261. }
  78262. Object.defineProperty(BouncingBehavior.prototype, "name", {
  78263. get: function () {
  78264. return "Bouncing";
  78265. },
  78266. enumerable: true,
  78267. configurable: true
  78268. });
  78269. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  78270. /**
  78271. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  78272. */
  78273. get: function () {
  78274. return this._autoTransitionRange;
  78275. },
  78276. /**
  78277. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  78278. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  78279. */
  78280. set: function (value) {
  78281. var _this = this;
  78282. if (this._autoTransitionRange === value) {
  78283. return;
  78284. }
  78285. this._autoTransitionRange = value;
  78286. var camera = this._attachedCamera;
  78287. if (!camera) {
  78288. return;
  78289. }
  78290. if (value) {
  78291. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  78292. if (!mesh) {
  78293. return;
  78294. }
  78295. mesh.computeWorldMatrix(true);
  78296. var diagonal = mesh.getBoundingInfo().diagonalLength;
  78297. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  78298. _this.upperRadiusTransitionRange = diagonal * 0.05;
  78299. });
  78300. }
  78301. else if (this._onMeshTargetChangedObserver) {
  78302. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  78303. }
  78304. },
  78305. enumerable: true,
  78306. configurable: true
  78307. });
  78308. BouncingBehavior.prototype.init = function () {
  78309. // Do notihng
  78310. };
  78311. BouncingBehavior.prototype.attach = function (camera) {
  78312. var _this = this;
  78313. this._attachedCamera = camera;
  78314. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  78315. if (!_this._attachedCamera) {
  78316. return;
  78317. }
  78318. // Add the bounce animation to the lower radius limit
  78319. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  78320. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  78321. }
  78322. // Add the bounce animation to the upper radius limit
  78323. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  78324. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  78325. }
  78326. });
  78327. };
  78328. BouncingBehavior.prototype.detach = function () {
  78329. if (!this._attachedCamera) {
  78330. return;
  78331. }
  78332. if (this._onAfterCheckInputsObserver) {
  78333. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  78334. }
  78335. if (this._onMeshTargetChangedObserver) {
  78336. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  78337. }
  78338. this._attachedCamera = null;
  78339. };
  78340. /**
  78341. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  78342. * @param radiusLimit The limit to check against.
  78343. * @return Bool to indicate if at limit.
  78344. */
  78345. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  78346. if (!this._attachedCamera) {
  78347. return false;
  78348. }
  78349. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  78350. return true;
  78351. }
  78352. return false;
  78353. };
  78354. /**
  78355. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  78356. * @param radiusDelta The delta by which to animate to. Can be negative.
  78357. */
  78358. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  78359. var _this = this;
  78360. if (!this._attachedCamera) {
  78361. return;
  78362. }
  78363. if (!this._radiusBounceTransition) {
  78364. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  78365. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  78366. }
  78367. // Prevent zoom until bounce has completed
  78368. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  78369. this._attachedCamera.wheelPrecision = Infinity;
  78370. this._attachedCamera.inertialRadiusOffset = 0;
  78371. // Animate to the radius limit
  78372. this.stopAllAnimations();
  78373. this._radiusIsAnimating = true;
  78374. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  78375. if (animatable) {
  78376. this._animatables.push(animatable);
  78377. }
  78378. };
  78379. /**
  78380. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  78381. */
  78382. BouncingBehavior.prototype._clearAnimationLocks = function () {
  78383. this._radiusIsAnimating = false;
  78384. if (this._attachedCamera) {
  78385. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  78386. }
  78387. };
  78388. /**
  78389. * Stops and removes all animations that have been applied to the camera
  78390. */
  78391. BouncingBehavior.prototype.stopAllAnimations = function () {
  78392. if (this._attachedCamera) {
  78393. this._attachedCamera.animations = [];
  78394. }
  78395. while (this._animatables.length) {
  78396. this._animatables[0].onAnimationEnd = null;
  78397. this._animatables[0].stop();
  78398. this._animatables.shift();
  78399. }
  78400. };
  78401. /**
  78402. * The easing function used by animations
  78403. */
  78404. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  78405. /**
  78406. * The easing mode used by animations
  78407. */
  78408. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  78409. return BouncingBehavior;
  78410. }());
  78411. BABYLON.BouncingBehavior = BouncingBehavior;
  78412. })(BABYLON || (BABYLON = {}));
  78413. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  78414. var BABYLON;
  78415. (function (BABYLON) {
  78416. var AutoRotationBehavior = /** @class */ (function () {
  78417. function AutoRotationBehavior() {
  78418. this._zoomStopsAnimation = false;
  78419. this._idleRotationSpeed = 0.05;
  78420. this._idleRotationWaitTime = 2000;
  78421. this._idleRotationSpinupTime = 2000;
  78422. this._isPointerDown = false;
  78423. this._lastFrameTime = null;
  78424. this._lastInteractionTime = -Infinity;
  78425. this._cameraRotationSpeed = 0;
  78426. this._lastFrameRadius = 0;
  78427. }
  78428. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  78429. get: function () {
  78430. return "AutoRotation";
  78431. },
  78432. enumerable: true,
  78433. configurable: true
  78434. });
  78435. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  78436. /**
  78437. * Gets the flag that indicates if user zooming should stop animation.
  78438. */
  78439. get: function () {
  78440. return this._zoomStopsAnimation;
  78441. },
  78442. /**
  78443. * Sets the flag that indicates if user zooming should stop animation.
  78444. */
  78445. set: function (flag) {
  78446. this._zoomStopsAnimation = flag;
  78447. },
  78448. enumerable: true,
  78449. configurable: true
  78450. });
  78451. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  78452. /**
  78453. * Gets the default speed at which the camera rotates around the model.
  78454. */
  78455. get: function () {
  78456. return this._idleRotationSpeed;
  78457. },
  78458. /**
  78459. * Sets the default speed at which the camera rotates around the model.
  78460. */
  78461. set: function (speed) {
  78462. this._idleRotationSpeed = speed;
  78463. },
  78464. enumerable: true,
  78465. configurable: true
  78466. });
  78467. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  78468. /**
  78469. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  78470. */
  78471. get: function () {
  78472. return this._idleRotationWaitTime;
  78473. },
  78474. /**
  78475. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  78476. */
  78477. set: function (time) {
  78478. this._idleRotationWaitTime = time;
  78479. },
  78480. enumerable: true,
  78481. configurable: true
  78482. });
  78483. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  78484. /**
  78485. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  78486. */
  78487. get: function () {
  78488. return this._idleRotationSpinupTime;
  78489. },
  78490. /**
  78491. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  78492. */
  78493. set: function (time) {
  78494. this._idleRotationSpinupTime = time;
  78495. },
  78496. enumerable: true,
  78497. configurable: true
  78498. });
  78499. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  78500. /**
  78501. * Gets a value indicating if the camera is currently rotating because of this behavior
  78502. */
  78503. get: function () {
  78504. return Math.abs(this._cameraRotationSpeed) > 0;
  78505. },
  78506. enumerable: true,
  78507. configurable: true
  78508. });
  78509. AutoRotationBehavior.prototype.init = function () {
  78510. // Do notihng
  78511. };
  78512. AutoRotationBehavior.prototype.attach = function (camera) {
  78513. var _this = this;
  78514. this._attachedCamera = camera;
  78515. var scene = this._attachedCamera.getScene();
  78516. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  78517. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  78518. _this._isPointerDown = true;
  78519. return;
  78520. }
  78521. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  78522. _this._isPointerDown = false;
  78523. }
  78524. });
  78525. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  78526. var now = BABYLON.Tools.Now;
  78527. var dt = 0;
  78528. if (_this._lastFrameTime != null) {
  78529. dt = now - _this._lastFrameTime;
  78530. }
  78531. _this._lastFrameTime = now;
  78532. // Stop the animation if there is user interaction and the animation should stop for this interaction
  78533. _this._applyUserInteraction();
  78534. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  78535. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  78536. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  78537. // Step camera rotation by rotation speed
  78538. if (_this._attachedCamera) {
  78539. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  78540. }
  78541. });
  78542. };
  78543. AutoRotationBehavior.prototype.detach = function () {
  78544. if (!this._attachedCamera) {
  78545. return;
  78546. }
  78547. var scene = this._attachedCamera.getScene();
  78548. if (this._onPrePointerObservableObserver) {
  78549. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  78550. }
  78551. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  78552. this._attachedCamera = null;
  78553. };
  78554. /**
  78555. * Returns true if user is scrolling.
  78556. * @return true if user is scrolling.
  78557. */
  78558. AutoRotationBehavior.prototype._userIsZooming = function () {
  78559. if (!this._attachedCamera) {
  78560. return false;
  78561. }
  78562. return this._attachedCamera.inertialRadiusOffset !== 0;
  78563. };
  78564. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  78565. if (!this._attachedCamera) {
  78566. return false;
  78567. }
  78568. var zoomHasHitLimit = false;
  78569. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  78570. zoomHasHitLimit = true;
  78571. }
  78572. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  78573. this._lastFrameRadius = this._attachedCamera.radius;
  78574. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  78575. };
  78576. /**
  78577. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  78578. */
  78579. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  78580. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  78581. this._lastInteractionTime = BABYLON.Tools.Now;
  78582. }
  78583. };
  78584. // Tools
  78585. AutoRotationBehavior.prototype._userIsMoving = function () {
  78586. if (!this._attachedCamera) {
  78587. return false;
  78588. }
  78589. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  78590. this._attachedCamera.inertialBetaOffset !== 0 ||
  78591. this._attachedCamera.inertialRadiusOffset !== 0 ||
  78592. this._attachedCamera.inertialPanningX !== 0 ||
  78593. this._attachedCamera.inertialPanningY !== 0 ||
  78594. this._isPointerDown;
  78595. };
  78596. return AutoRotationBehavior;
  78597. }());
  78598. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  78599. })(BABYLON || (BABYLON = {}));
  78600. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  78601. var BABYLON;
  78602. (function (BABYLON) {
  78603. var NullEngineOptions = /** @class */ (function () {
  78604. function NullEngineOptions() {
  78605. this.renderWidth = 512;
  78606. this.renderHeight = 256;
  78607. this.textureSize = 512;
  78608. this.deterministicLockstep = false;
  78609. this.lockstepMaxSteps = 4;
  78610. }
  78611. return NullEngineOptions;
  78612. }());
  78613. BABYLON.NullEngineOptions = NullEngineOptions;
  78614. /**
  78615. * The null engine class provides support for headless version of babylon.js.
  78616. * This can be used in server side scenario or for testing purposes
  78617. */
  78618. var NullEngine = /** @class */ (function (_super) {
  78619. __extends(NullEngine, _super);
  78620. function NullEngine(options) {
  78621. if (options === void 0) { options = new NullEngineOptions(); }
  78622. var _this = _super.call(this, null) || this;
  78623. if (options.deterministicLockstep === undefined) {
  78624. options.deterministicLockstep = false;
  78625. }
  78626. if (options.lockstepMaxSteps === undefined) {
  78627. options.lockstepMaxSteps = 4;
  78628. }
  78629. _this._options = options;
  78630. // Init caps
  78631. // We consider we are on a webgl1 capable device
  78632. _this._caps = new BABYLON.EngineCapabilities();
  78633. _this._caps.maxTexturesImageUnits = 16;
  78634. _this._caps.maxVertexTextureImageUnits = 16;
  78635. _this._caps.maxTextureSize = 512;
  78636. _this._caps.maxCubemapTextureSize = 512;
  78637. _this._caps.maxRenderTextureSize = 512;
  78638. _this._caps.maxVertexAttribs = 16;
  78639. _this._caps.maxVaryingVectors = 16;
  78640. _this._caps.maxFragmentUniformVectors = 16;
  78641. _this._caps.maxVertexUniformVectors = 16;
  78642. // Extensions
  78643. _this._caps.standardDerivatives = false;
  78644. _this._caps.astc = null;
  78645. _this._caps.s3tc = null;
  78646. _this._caps.pvrtc = null;
  78647. _this._caps.etc1 = null;
  78648. _this._caps.etc2 = null;
  78649. _this._caps.textureAnisotropicFilterExtension = null;
  78650. _this._caps.maxAnisotropy = 0;
  78651. _this._caps.uintIndices = false;
  78652. _this._caps.fragmentDepthSupported = false;
  78653. _this._caps.highPrecisionShaderSupported = true;
  78654. _this._caps.colorBufferFloat = false;
  78655. _this._caps.textureFloat = false;
  78656. _this._caps.textureFloatLinearFiltering = false;
  78657. _this._caps.textureFloatRender = false;
  78658. _this._caps.textureHalfFloat = false;
  78659. _this._caps.textureHalfFloatLinearFiltering = false;
  78660. _this._caps.textureHalfFloatRender = false;
  78661. _this._caps.textureLOD = false;
  78662. _this._caps.drawBuffersExtension = false;
  78663. _this._caps.depthTextureExtension = false;
  78664. _this._caps.vertexArrayObject = false;
  78665. _this._caps.instancedArrays = false;
  78666. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  78667. // Wrappers
  78668. if (typeof URL === "undefined") {
  78669. URL = {
  78670. createObjectURL: function () { },
  78671. revokeObjectURL: function () { }
  78672. };
  78673. }
  78674. if (typeof Blob === "undefined") {
  78675. Blob = function () { };
  78676. }
  78677. return _this;
  78678. }
  78679. NullEngine.prototype.isDeterministicLockStep = function () {
  78680. return this._options.deterministicLockstep;
  78681. };
  78682. NullEngine.prototype.getLockstepMaxSteps = function () {
  78683. return this._options.lockstepMaxSteps;
  78684. };
  78685. NullEngine.prototype.createVertexBuffer = function (vertices) {
  78686. return {
  78687. capacity: 0,
  78688. references: 1,
  78689. is32Bits: false
  78690. };
  78691. };
  78692. NullEngine.prototype.createIndexBuffer = function (indices) {
  78693. return {
  78694. capacity: 0,
  78695. references: 1,
  78696. is32Bits: false
  78697. };
  78698. };
  78699. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  78700. if (stencil === void 0) { stencil = false; }
  78701. };
  78702. NullEngine.prototype.getRenderWidth = function (useScreen) {
  78703. if (useScreen === void 0) { useScreen = false; }
  78704. if (!useScreen && this._currentRenderTarget) {
  78705. return this._currentRenderTarget.width;
  78706. }
  78707. return this._options.renderWidth;
  78708. };
  78709. NullEngine.prototype.getRenderHeight = function (useScreen) {
  78710. if (useScreen === void 0) { useScreen = false; }
  78711. if (!useScreen && this._currentRenderTarget) {
  78712. return this._currentRenderTarget.height;
  78713. }
  78714. return this._options.renderHeight;
  78715. };
  78716. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  78717. this._cachedViewport = viewport;
  78718. };
  78719. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  78720. return {
  78721. transformFeedback: null,
  78722. __SPECTOR_rebuildProgram: null
  78723. };
  78724. };
  78725. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  78726. return [];
  78727. };
  78728. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  78729. return [];
  78730. };
  78731. NullEngine.prototype.bindSamplers = function (effect) {
  78732. this._currentEffect = null;
  78733. };
  78734. NullEngine.prototype.enableEffect = function (effect) {
  78735. this._currentEffect = effect;
  78736. if (effect.onBind) {
  78737. effect.onBind(effect);
  78738. }
  78739. effect.onBindObservable.notifyObservers(effect);
  78740. };
  78741. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  78742. if (zOffset === void 0) { zOffset = 0; }
  78743. if (reverseSide === void 0) { reverseSide = false; }
  78744. };
  78745. NullEngine.prototype.setIntArray = function (uniform, array) {
  78746. };
  78747. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  78748. };
  78749. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  78750. };
  78751. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  78752. };
  78753. NullEngine.prototype.setFloatArray = function (uniform, array) {
  78754. };
  78755. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  78756. };
  78757. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  78758. };
  78759. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  78760. };
  78761. NullEngine.prototype.setArray = function (uniform, array) {
  78762. };
  78763. NullEngine.prototype.setArray2 = function (uniform, array) {
  78764. };
  78765. NullEngine.prototype.setArray3 = function (uniform, array) {
  78766. };
  78767. NullEngine.prototype.setArray4 = function (uniform, array) {
  78768. };
  78769. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  78770. };
  78771. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  78772. };
  78773. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  78774. };
  78775. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  78776. };
  78777. NullEngine.prototype.setFloat = function (uniform, value) {
  78778. };
  78779. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  78780. };
  78781. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  78782. };
  78783. NullEngine.prototype.setBool = function (uniform, bool) {
  78784. };
  78785. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  78786. };
  78787. NullEngine.prototype.setColor3 = function (uniform, color3) {
  78788. };
  78789. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  78790. };
  78791. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  78792. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  78793. if (this._alphaMode === mode) {
  78794. return;
  78795. }
  78796. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  78797. if (!noDepthWriteChange) {
  78798. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  78799. }
  78800. this._alphaMode = mode;
  78801. };
  78802. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  78803. };
  78804. NullEngine.prototype.wipeCaches = function (bruteForce) {
  78805. if (this.preventCacheWipeBetweenFrames) {
  78806. return;
  78807. }
  78808. this.resetTextureCache();
  78809. this._currentEffect = null;
  78810. if (bruteForce) {
  78811. this._currentProgram = null;
  78812. this._stencilState.reset();
  78813. this._depthCullingState.reset();
  78814. this.setDepthFunctionToLessOrEqual();
  78815. this._alphaState.reset();
  78816. }
  78817. this._cachedVertexBuffers = null;
  78818. this._cachedIndexBuffer = null;
  78819. this._cachedEffectForVertexBuffers = null;
  78820. };
  78821. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  78822. };
  78823. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  78824. };
  78825. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  78826. };
  78827. NullEngine.prototype._createTexture = function () {
  78828. return {};
  78829. };
  78830. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  78831. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  78832. if (onLoad === void 0) { onLoad = null; }
  78833. if (onError === void 0) { onError = null; }
  78834. if (buffer === void 0) { buffer = null; }
  78835. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  78836. var url = String(urlArg);
  78837. texture.url = url;
  78838. texture.generateMipMaps = !noMipmap;
  78839. texture.samplingMode = samplingMode;
  78840. texture.invertY = invertY;
  78841. texture.baseWidth = this._options.textureSize;
  78842. texture.baseHeight = this._options.textureSize;
  78843. texture.width = this._options.textureSize;
  78844. texture.height = this._options.textureSize;
  78845. if (format) {
  78846. texture.format = format;
  78847. }
  78848. texture.isReady = true;
  78849. if (onLoad) {
  78850. onLoad();
  78851. }
  78852. return texture;
  78853. };
  78854. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  78855. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  78856. if (options !== undefined && typeof options === "object") {
  78857. fullOptions.generateMipMaps = options.generateMipMaps;
  78858. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  78859. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  78860. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  78861. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  78862. }
  78863. else {
  78864. fullOptions.generateMipMaps = options;
  78865. fullOptions.generateDepthBuffer = true;
  78866. fullOptions.generateStencilBuffer = false;
  78867. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  78868. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  78869. }
  78870. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  78871. var width = size.width || size;
  78872. var height = size.height || size;
  78873. texture._depthStencilBuffer = {};
  78874. texture._framebuffer = {};
  78875. texture.baseWidth = width;
  78876. texture.baseHeight = height;
  78877. texture.width = width;
  78878. texture.height = height;
  78879. texture.isReady = true;
  78880. texture.samples = 1;
  78881. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  78882. texture.samplingMode = fullOptions.samplingMode;
  78883. texture.type = fullOptions.type;
  78884. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  78885. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  78886. return texture;
  78887. };
  78888. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  78889. texture.samplingMode = samplingMode;
  78890. };
  78891. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  78892. if (this._currentRenderTarget) {
  78893. this.unBindFramebuffer(this._currentRenderTarget);
  78894. }
  78895. this._currentRenderTarget = texture;
  78896. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  78897. if (this._cachedViewport && !forceFullscreenViewport) {
  78898. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  78899. }
  78900. };
  78901. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  78902. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  78903. this._currentRenderTarget = null;
  78904. if (onBeforeUnbind) {
  78905. if (texture._MSAAFramebuffer) {
  78906. this._currentFramebuffer = texture._framebuffer;
  78907. }
  78908. onBeforeUnbind();
  78909. }
  78910. this._currentFramebuffer = null;
  78911. };
  78912. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  78913. var vbo = {
  78914. capacity: 1,
  78915. references: 1,
  78916. is32Bits: false
  78917. };
  78918. return vbo;
  78919. };
  78920. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  78921. if (offset === void 0) { offset = 0; }
  78922. };
  78923. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  78924. };
  78925. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  78926. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  78927. this._boundTexturesCache[this._activeChannel] = texture;
  78928. }
  78929. };
  78930. NullEngine.prototype._bindTexture = function (channel, texture) {
  78931. if (channel < 0) {
  78932. return;
  78933. }
  78934. this._bindTextureDirectly(0, texture);
  78935. };
  78936. NullEngine.prototype._releaseBuffer = function (buffer) {
  78937. buffer.references--;
  78938. if (buffer.references === 0) {
  78939. return true;
  78940. }
  78941. return false;
  78942. };
  78943. return NullEngine;
  78944. }(BABYLON.Engine));
  78945. BABYLON.NullEngine = NullEngine;
  78946. })(BABYLON || (BABYLON = {}));
  78947. //# sourceMappingURL=babylon.nullEngine.js.map
  78948. var BABYLON;
  78949. (function (BABYLON) {
  78950. /**
  78951. * This class can be used to get instrumentation data from a Babylon engine
  78952. */
  78953. var EngineInstrumentation = /** @class */ (function () {
  78954. function EngineInstrumentation(engine) {
  78955. this.engine = engine;
  78956. this._captureGPUFrameTime = false;
  78957. this._gpuFrameTime = new BABYLON.PerfCounter();
  78958. this._captureShaderCompilationTime = false;
  78959. this._shaderCompilationTime = new BABYLON.PerfCounter();
  78960. // Observers
  78961. this._onBeginFrameObserver = null;
  78962. this._onEndFrameObserver = null;
  78963. this._onBeforeShaderCompilationObserver = null;
  78964. this._onAfterShaderCompilationObserver = null;
  78965. }
  78966. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  78967. // Properties
  78968. /**
  78969. * Gets the perf counter used for GPU frame time
  78970. */
  78971. get: function () {
  78972. return this._gpuFrameTime;
  78973. },
  78974. enumerable: true,
  78975. configurable: true
  78976. });
  78977. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  78978. /**
  78979. * Gets the GPU frame time capture status
  78980. */
  78981. get: function () {
  78982. return this._captureGPUFrameTime;
  78983. },
  78984. /**
  78985. * Enable or disable the GPU frame time capture
  78986. */
  78987. set: function (value) {
  78988. var _this = this;
  78989. if (value === this._captureGPUFrameTime) {
  78990. return;
  78991. }
  78992. this._captureGPUFrameTime = value;
  78993. if (value) {
  78994. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  78995. if (!_this._gpuFrameTimeToken) {
  78996. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  78997. }
  78998. });
  78999. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  79000. if (!_this._gpuFrameTimeToken) {
  79001. return;
  79002. }
  79003. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  79004. if (time > -1) {
  79005. _this._gpuFrameTimeToken = null;
  79006. _this._gpuFrameTime.fetchNewFrame();
  79007. _this._gpuFrameTime.addCount(time, true);
  79008. }
  79009. });
  79010. }
  79011. else {
  79012. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  79013. this._onBeginFrameObserver = null;
  79014. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  79015. this._onEndFrameObserver = null;
  79016. }
  79017. },
  79018. enumerable: true,
  79019. configurable: true
  79020. });
  79021. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  79022. /**
  79023. * Gets the perf counter used for shader compilation time
  79024. */
  79025. get: function () {
  79026. return this._shaderCompilationTime;
  79027. },
  79028. enumerable: true,
  79029. configurable: true
  79030. });
  79031. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  79032. /**
  79033. * Gets the shader compilation time capture status
  79034. */
  79035. get: function () {
  79036. return this._captureShaderCompilationTime;
  79037. },
  79038. /**
  79039. * Enable or disable the shader compilation time capture
  79040. */
  79041. set: function (value) {
  79042. var _this = this;
  79043. if (value === this._captureShaderCompilationTime) {
  79044. return;
  79045. }
  79046. this._captureShaderCompilationTime = value;
  79047. if (value) {
  79048. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  79049. _this._shaderCompilationTime.fetchNewFrame();
  79050. _this._shaderCompilationTime.beginMonitoring();
  79051. });
  79052. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  79053. _this._shaderCompilationTime.endMonitoring();
  79054. });
  79055. }
  79056. else {
  79057. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  79058. this._onBeforeShaderCompilationObserver = null;
  79059. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  79060. this._onAfterShaderCompilationObserver = null;
  79061. }
  79062. },
  79063. enumerable: true,
  79064. configurable: true
  79065. });
  79066. EngineInstrumentation.prototype.dispose = function () {
  79067. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  79068. this._onBeginFrameObserver = null;
  79069. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  79070. this._onEndFrameObserver = null;
  79071. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  79072. this._onBeforeShaderCompilationObserver = null;
  79073. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  79074. this._onAfterShaderCompilationObserver = null;
  79075. this.engine = null;
  79076. };
  79077. return EngineInstrumentation;
  79078. }());
  79079. BABYLON.EngineInstrumentation = EngineInstrumentation;
  79080. })(BABYLON || (BABYLON = {}));
  79081. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  79082. var BABYLON;
  79083. (function (BABYLON) {
  79084. /**
  79085. * This class can be used to get instrumentation data from a Babylon engine
  79086. */
  79087. var SceneInstrumentation = /** @class */ (function () {
  79088. function SceneInstrumentation(scene) {
  79089. var _this = this;
  79090. this.scene = scene;
  79091. this._captureActiveMeshesEvaluationTime = false;
  79092. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  79093. this._captureRenderTargetsRenderTime = false;
  79094. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  79095. this._captureFrameTime = false;
  79096. this._frameTime = new BABYLON.PerfCounter();
  79097. this._captureRenderTime = false;
  79098. this._renderTime = new BABYLON.PerfCounter();
  79099. this._captureInterFrameTime = false;
  79100. this._interFrameTime = new BABYLON.PerfCounter();
  79101. this._captureParticlesRenderTime = false;
  79102. this._particlesRenderTime = new BABYLON.PerfCounter();
  79103. this._captureSpritesRenderTime = false;
  79104. this._spritesRenderTime = new BABYLON.PerfCounter();
  79105. this._capturePhysicsTime = false;
  79106. this._physicsTime = new BABYLON.PerfCounter();
  79107. this._captureAnimationsTime = false;
  79108. this._animationsTime = new BABYLON.PerfCounter();
  79109. // Observers
  79110. this._onBeforeActiveMeshesEvaluationObserver = null;
  79111. this._onAfterActiveMeshesEvaluationObserver = null;
  79112. this._onBeforeRenderTargetsRenderObserver = null;
  79113. this._onAfterRenderTargetsRenderObserver = null;
  79114. this._onAfterRenderObserver = null;
  79115. this._onBeforeDrawPhaseObserver = null;
  79116. this._onAfterDrawPhaseObserver = null;
  79117. this._onBeforeAnimationsObserver = null;
  79118. this._onBeforeParticlesRenderingObserver = null;
  79119. this._onAfterParticlesRenderingObserver = null;
  79120. this._onBeforeSpritesRenderingObserver = null;
  79121. this._onAfterSpritesRenderingObserver = null;
  79122. this._onBeforePhysicsObserver = null;
  79123. this._onAfterPhysicsObserver = null;
  79124. this._onAfterAnimationsObserver = null;
  79125. // Before render
  79126. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  79127. if (_this._captureActiveMeshesEvaluationTime) {
  79128. _this._activeMeshesEvaluationTime.fetchNewFrame();
  79129. }
  79130. if (_this._captureRenderTargetsRenderTime) {
  79131. _this._renderTargetsRenderTime.fetchNewFrame();
  79132. }
  79133. if (_this._captureFrameTime) {
  79134. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  79135. _this._frameTime.beginMonitoring();
  79136. }
  79137. if (_this._captureInterFrameTime) {
  79138. _this._interFrameTime.endMonitoring();
  79139. }
  79140. if (_this._captureParticlesRenderTime) {
  79141. _this._particlesRenderTime.fetchNewFrame();
  79142. }
  79143. if (_this._captureSpritesRenderTime) {
  79144. _this._spritesRenderTime.fetchNewFrame();
  79145. }
  79146. if (_this._captureAnimationsTime) {
  79147. _this._animationsTime.beginMonitoring();
  79148. }
  79149. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  79150. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  79151. });
  79152. // After render
  79153. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  79154. if (_this._captureFrameTime) {
  79155. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  79156. _this._frameTime.endMonitoring();
  79157. }
  79158. if (_this._captureRenderTime) {
  79159. _this._renderTime.endMonitoring(false);
  79160. }
  79161. if (_this._captureInterFrameTime) {
  79162. _this._interFrameTime.beginMonitoring();
  79163. }
  79164. });
  79165. }
  79166. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  79167. // Properties
  79168. /**
  79169. * Gets the perf counter used for active meshes evaluation time
  79170. */
  79171. get: function () {
  79172. return this._activeMeshesEvaluationTime;
  79173. },
  79174. enumerable: true,
  79175. configurable: true
  79176. });
  79177. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  79178. /**
  79179. * Gets the active meshes evaluation time capture status
  79180. */
  79181. get: function () {
  79182. return this._captureActiveMeshesEvaluationTime;
  79183. },
  79184. /**
  79185. * Enable or disable the active meshes evaluation time capture
  79186. */
  79187. set: function (value) {
  79188. var _this = this;
  79189. if (value === this._captureActiveMeshesEvaluationTime) {
  79190. return;
  79191. }
  79192. this._captureActiveMeshesEvaluationTime = value;
  79193. if (value) {
  79194. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  79195. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  79196. _this._activeMeshesEvaluationTime.beginMonitoring();
  79197. });
  79198. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  79199. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  79200. _this._activeMeshesEvaluationTime.endMonitoring();
  79201. });
  79202. }
  79203. else {
  79204. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  79205. this._onBeforeActiveMeshesEvaluationObserver = null;
  79206. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  79207. this._onAfterActiveMeshesEvaluationObserver = null;
  79208. }
  79209. },
  79210. enumerable: true,
  79211. configurable: true
  79212. });
  79213. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  79214. /**
  79215. * Gets the perf counter used for render targets render time
  79216. */
  79217. get: function () {
  79218. return this._renderTargetsRenderTime;
  79219. },
  79220. enumerable: true,
  79221. configurable: true
  79222. });
  79223. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  79224. /**
  79225. * Gets the render targets render time capture status
  79226. */
  79227. get: function () {
  79228. return this._captureRenderTargetsRenderTime;
  79229. },
  79230. /**
  79231. * Enable or disable the render targets render time capture
  79232. */
  79233. set: function (value) {
  79234. var _this = this;
  79235. if (value === this._captureRenderTargetsRenderTime) {
  79236. return;
  79237. }
  79238. this._captureRenderTargetsRenderTime = value;
  79239. if (value) {
  79240. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  79241. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  79242. _this._renderTargetsRenderTime.beginMonitoring();
  79243. });
  79244. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  79245. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  79246. _this._renderTargetsRenderTime.endMonitoring(false);
  79247. });
  79248. }
  79249. else {
  79250. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  79251. this._onBeforeRenderTargetsRenderObserver = null;
  79252. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  79253. this._onAfterRenderTargetsRenderObserver = null;
  79254. }
  79255. },
  79256. enumerable: true,
  79257. configurable: true
  79258. });
  79259. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  79260. /**
  79261. * Gets the perf counter used for particles render time
  79262. */
  79263. get: function () {
  79264. return this._particlesRenderTime;
  79265. },
  79266. enumerable: true,
  79267. configurable: true
  79268. });
  79269. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  79270. /**
  79271. * Gets the particles render time capture status
  79272. */
  79273. get: function () {
  79274. return this._captureParticlesRenderTime;
  79275. },
  79276. /**
  79277. * Enable or disable the particles render time capture
  79278. */
  79279. set: function (value) {
  79280. var _this = this;
  79281. if (value === this._captureParticlesRenderTime) {
  79282. return;
  79283. }
  79284. this._captureParticlesRenderTime = value;
  79285. if (value) {
  79286. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  79287. BABYLON.Tools.StartPerformanceCounter("Particles");
  79288. _this._particlesRenderTime.beginMonitoring();
  79289. });
  79290. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  79291. BABYLON.Tools.EndPerformanceCounter("Particles");
  79292. _this._particlesRenderTime.endMonitoring(false);
  79293. });
  79294. }
  79295. else {
  79296. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  79297. this._onBeforeParticlesRenderingObserver = null;
  79298. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  79299. this._onAfterParticlesRenderingObserver = null;
  79300. }
  79301. },
  79302. enumerable: true,
  79303. configurable: true
  79304. });
  79305. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  79306. /**
  79307. * Gets the perf counter used for sprites render time
  79308. */
  79309. get: function () {
  79310. return this._spritesRenderTime;
  79311. },
  79312. enumerable: true,
  79313. configurable: true
  79314. });
  79315. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  79316. /**
  79317. * Gets the sprites render time capture status
  79318. */
  79319. get: function () {
  79320. return this._captureSpritesRenderTime;
  79321. },
  79322. /**
  79323. * Enable or disable the sprites render time capture
  79324. */
  79325. set: function (value) {
  79326. var _this = this;
  79327. if (value === this._captureSpritesRenderTime) {
  79328. return;
  79329. }
  79330. this._captureSpritesRenderTime = value;
  79331. if (value) {
  79332. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  79333. BABYLON.Tools.StartPerformanceCounter("Sprites");
  79334. _this._spritesRenderTime.beginMonitoring();
  79335. });
  79336. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  79337. BABYLON.Tools.EndPerformanceCounter("Sprites");
  79338. _this._spritesRenderTime.endMonitoring(false);
  79339. });
  79340. }
  79341. else {
  79342. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  79343. this._onBeforeSpritesRenderingObserver = null;
  79344. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  79345. this._onAfterSpritesRenderingObserver = null;
  79346. }
  79347. },
  79348. enumerable: true,
  79349. configurable: true
  79350. });
  79351. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  79352. /**
  79353. * Gets the perf counter used for physics time
  79354. */
  79355. get: function () {
  79356. return this._physicsTime;
  79357. },
  79358. enumerable: true,
  79359. configurable: true
  79360. });
  79361. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  79362. /**
  79363. * Gets the physics time capture status
  79364. */
  79365. get: function () {
  79366. return this._capturePhysicsTime;
  79367. },
  79368. /**
  79369. * Enable or disable the physics time capture
  79370. */
  79371. set: function (value) {
  79372. var _this = this;
  79373. if (value === this._capturePhysicsTime) {
  79374. return;
  79375. }
  79376. this._capturePhysicsTime = value;
  79377. if (value) {
  79378. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  79379. BABYLON.Tools.StartPerformanceCounter("Physics");
  79380. _this._physicsTime.beginMonitoring();
  79381. });
  79382. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  79383. BABYLON.Tools.EndPerformanceCounter("Physics");
  79384. _this._physicsTime.endMonitoring();
  79385. });
  79386. }
  79387. else {
  79388. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  79389. this._onBeforePhysicsObserver = null;
  79390. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  79391. this._onAfterPhysicsObserver = null;
  79392. }
  79393. },
  79394. enumerable: true,
  79395. configurable: true
  79396. });
  79397. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  79398. /**
  79399. * Gets the perf counter used for animations time
  79400. */
  79401. get: function () {
  79402. return this._animationsTime;
  79403. },
  79404. enumerable: true,
  79405. configurable: true
  79406. });
  79407. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  79408. /**
  79409. * Gets the animations time capture status
  79410. */
  79411. get: function () {
  79412. return this._captureAnimationsTime;
  79413. },
  79414. /**
  79415. * Enable or disable the animations time capture
  79416. */
  79417. set: function (value) {
  79418. var _this = this;
  79419. if (value === this._captureAnimationsTime) {
  79420. return;
  79421. }
  79422. this._captureAnimationsTime = value;
  79423. if (value) {
  79424. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  79425. _this._animationsTime.endMonitoring();
  79426. });
  79427. }
  79428. else {
  79429. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  79430. this._onAfterAnimationsObserver = null;
  79431. }
  79432. },
  79433. enumerable: true,
  79434. configurable: true
  79435. });
  79436. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  79437. /**
  79438. * Gets the perf counter used for frame time capture
  79439. */
  79440. get: function () {
  79441. return this._frameTime;
  79442. },
  79443. enumerable: true,
  79444. configurable: true
  79445. });
  79446. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  79447. /**
  79448. * Gets the frame time capture status
  79449. */
  79450. get: function () {
  79451. return this._captureFrameTime;
  79452. },
  79453. /**
  79454. * Enable or disable the frame time capture
  79455. */
  79456. set: function (value) {
  79457. this._captureFrameTime = value;
  79458. },
  79459. enumerable: true,
  79460. configurable: true
  79461. });
  79462. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  79463. /**
  79464. * Gets the perf counter used for inter-frames time capture
  79465. */
  79466. get: function () {
  79467. return this._interFrameTime;
  79468. },
  79469. enumerable: true,
  79470. configurable: true
  79471. });
  79472. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  79473. /**
  79474. * Gets the inter-frames time capture status
  79475. */
  79476. get: function () {
  79477. return this._captureInterFrameTime;
  79478. },
  79479. /**
  79480. * Enable or disable the inter-frames time capture
  79481. */
  79482. set: function (value) {
  79483. this._captureInterFrameTime = value;
  79484. },
  79485. enumerable: true,
  79486. configurable: true
  79487. });
  79488. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  79489. /**
  79490. * Gets the perf counter used for render time capture
  79491. */
  79492. get: function () {
  79493. return this._renderTime;
  79494. },
  79495. enumerable: true,
  79496. configurable: true
  79497. });
  79498. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  79499. /**
  79500. * Gets the render time capture status
  79501. */
  79502. get: function () {
  79503. return this._captureRenderTime;
  79504. },
  79505. /**
  79506. * Enable or disable the render time capture
  79507. */
  79508. set: function (value) {
  79509. var _this = this;
  79510. if (value === this._captureRenderTime) {
  79511. return;
  79512. }
  79513. this._captureRenderTime = value;
  79514. if (value) {
  79515. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  79516. _this._renderTime.beginMonitoring();
  79517. BABYLON.Tools.StartPerformanceCounter("Main render");
  79518. });
  79519. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  79520. _this._renderTime.endMonitoring(false);
  79521. BABYLON.Tools.EndPerformanceCounter("Main render");
  79522. });
  79523. }
  79524. else {
  79525. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  79526. this._onBeforeDrawPhaseObserver = null;
  79527. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  79528. this._onAfterDrawPhaseObserver = null;
  79529. }
  79530. },
  79531. enumerable: true,
  79532. configurable: true
  79533. });
  79534. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  79535. /**
  79536. * Gets the perf counter used for draw calls
  79537. */
  79538. get: function () {
  79539. return this.scene.getEngine()._drawCalls;
  79540. },
  79541. enumerable: true,
  79542. configurable: true
  79543. });
  79544. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  79545. /**
  79546. * Gets the perf counter used for texture collisions
  79547. */
  79548. get: function () {
  79549. return this.scene.getEngine()._textureCollisions;
  79550. },
  79551. enumerable: true,
  79552. configurable: true
  79553. });
  79554. SceneInstrumentation.prototype.dispose = function () {
  79555. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  79556. this._onAfterRenderObserver = null;
  79557. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  79558. this._onBeforeActiveMeshesEvaluationObserver = null;
  79559. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  79560. this._onAfterActiveMeshesEvaluationObserver = null;
  79561. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  79562. this._onBeforeRenderTargetsRenderObserver = null;
  79563. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  79564. this._onAfterRenderTargetsRenderObserver = null;
  79565. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  79566. this._onBeforeAnimationsObserver = null;
  79567. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  79568. this._onBeforeParticlesRenderingObserver = null;
  79569. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  79570. this._onAfterParticlesRenderingObserver = null;
  79571. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  79572. this._onBeforeSpritesRenderingObserver = null;
  79573. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  79574. this._onAfterSpritesRenderingObserver = null;
  79575. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  79576. this._onBeforeDrawPhaseObserver = null;
  79577. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  79578. this._onAfterDrawPhaseObserver = null;
  79579. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  79580. this._onBeforePhysicsObserver = null;
  79581. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  79582. this._onAfterPhysicsObserver = null;
  79583. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  79584. this._onAfterAnimationsObserver = null;
  79585. this.scene = null;
  79586. };
  79587. return SceneInstrumentation;
  79588. }());
  79589. BABYLON.SceneInstrumentation = SceneInstrumentation;
  79590. })(BABYLON || (BABYLON = {}));
  79591. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  79592. var BABYLON;
  79593. (function (BABYLON) {
  79594. var _TimeToken = /** @class */ (function () {
  79595. function _TimeToken() {
  79596. this._timeElapsedQueryEnded = false;
  79597. }
  79598. return _TimeToken;
  79599. }());
  79600. BABYLON._TimeToken = _TimeToken;
  79601. })(BABYLON || (BABYLON = {}));
  79602. //# sourceMappingURL=babylon.timeToken.js.map
  79603. var BABYLON;
  79604. (function (BABYLON) {
  79605. /**
  79606. * Background material defines definition.
  79607. */
  79608. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  79609. __extends(BackgroundMaterialDefines, _super);
  79610. /**
  79611. * Constructor of the defines.
  79612. */
  79613. function BackgroundMaterialDefines() {
  79614. var _this = _super.call(this) || this;
  79615. /**
  79616. * True if the diffuse texture is in use.
  79617. */
  79618. _this.DIFFUSE = false;
  79619. /**
  79620. * The direct UV channel to use.
  79621. */
  79622. _this.DIFFUSEDIRECTUV = 0;
  79623. /**
  79624. * True if the diffuse texture is in gamma space.
  79625. */
  79626. _this.GAMMADIFFUSE = false;
  79627. /**
  79628. * True if the diffuse texture has opacity in the alpha channel.
  79629. */
  79630. _this.DIFFUSEHASALPHA = false;
  79631. /**
  79632. * True if you want the material to fade to transparent at grazing angle.
  79633. */
  79634. _this.OPACITYFRESNEL = false;
  79635. /**
  79636. * True if an extra blur needs to be added in the reflection.
  79637. */
  79638. _this.REFLECTIONBLUR = false;
  79639. /**
  79640. * True if you want the material to fade to reflection at grazing angle.
  79641. */
  79642. _this.REFLECTIONFRESNEL = false;
  79643. /**
  79644. * True if you want the material to falloff as far as you move away from the scene center.
  79645. */
  79646. _this.REFLECTIONFALLOFF = false;
  79647. /**
  79648. * False if the current Webgl implementation does not support the texture lod extension.
  79649. */
  79650. _this.TEXTURELODSUPPORT = false;
  79651. /**
  79652. * True to ensure the data are premultiplied.
  79653. */
  79654. _this.PREMULTIPLYALPHA = false;
  79655. /**
  79656. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  79657. */
  79658. _this.USERGBCOLOR = false;
  79659. /**
  79660. * True to add noise in order to reduce the banding effect.
  79661. */
  79662. _this.NOISE = false;
  79663. // Image Processing Configuration.
  79664. _this.IMAGEPROCESSING = false;
  79665. _this.VIGNETTE = false;
  79666. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  79667. _this.VIGNETTEBLENDMODEOPAQUE = false;
  79668. _this.TONEMAPPING = false;
  79669. _this.CONTRAST = false;
  79670. _this.COLORCURVES = false;
  79671. _this.COLORGRADING = false;
  79672. _this.COLORGRADING3D = false;
  79673. _this.SAMPLER3DGREENDEPTH = false;
  79674. _this.SAMPLER3DBGRMAP = false;
  79675. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  79676. _this.EXPOSURE = false;
  79677. // Reflection.
  79678. _this.REFLECTION = false;
  79679. _this.REFLECTIONMAP_3D = false;
  79680. _this.REFLECTIONMAP_SPHERICAL = false;
  79681. _this.REFLECTIONMAP_PLANAR = false;
  79682. _this.REFLECTIONMAP_CUBIC = false;
  79683. _this.REFLECTIONMAP_PROJECTION = false;
  79684. _this.REFLECTIONMAP_SKYBOX = false;
  79685. _this.REFLECTIONMAP_EXPLICIT = false;
  79686. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  79687. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  79688. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  79689. _this.INVERTCUBICMAP = false;
  79690. _this.REFLECTIONMAP_OPPOSITEZ = false;
  79691. _this.LODINREFLECTIONALPHA = false;
  79692. _this.GAMMAREFLECTION = false;
  79693. // Default BJS.
  79694. _this.MAINUV1 = false;
  79695. _this.MAINUV2 = false;
  79696. _this.UV1 = false;
  79697. _this.UV2 = false;
  79698. _this.CLIPPLANE = false;
  79699. _this.POINTSIZE = false;
  79700. _this.FOG = false;
  79701. _this.NORMAL = false;
  79702. _this.NUM_BONE_INFLUENCERS = 0;
  79703. _this.BonesPerMesh = 0;
  79704. _this.INSTANCES = false;
  79705. _this.SHADOWFLOAT = false;
  79706. _this.rebuild();
  79707. return _this;
  79708. }
  79709. return BackgroundMaterialDefines;
  79710. }(BABYLON.MaterialDefines));
  79711. /**
  79712. * Background material used to create an efficient environement around your scene.
  79713. */
  79714. var BackgroundMaterial = /** @class */ (function (_super) {
  79715. __extends(BackgroundMaterial, _super);
  79716. /**
  79717. * constructor
  79718. * @param name The name of the material
  79719. * @param scene The scene to add the material to
  79720. */
  79721. function BackgroundMaterial(name, scene) {
  79722. var _this = _super.call(this, name, scene) || this;
  79723. _this.primaryColor = BABYLON.Color3.White();
  79724. _this.primaryLevel = 1;
  79725. _this.secondaryColor = BABYLON.Color3.Gray();
  79726. _this.secondaryLevel = 1;
  79727. _this.tertiaryColor = BABYLON.Color3.Black();
  79728. _this.tertiaryLevel = 1;
  79729. _this.reflectionTexture = null;
  79730. _this.reflectionBlur = 0;
  79731. _this.diffuseTexture = null;
  79732. /**
  79733. * Specify the list of lights casting shadow on the material.
  79734. * All scene shadow lights will be included if null.
  79735. */
  79736. _this._shadowLights = null;
  79737. _this.shadowLights = null;
  79738. _this.shadowBlurScale = 1;
  79739. _this.shadowLevel = 0;
  79740. _this.sceneCenter = BABYLON.Vector3.Zero();
  79741. _this.opacityFresnel = true;
  79742. _this.reflectionFresnel = false;
  79743. _this.reflectionFalloffDistance = 0.0;
  79744. _this.reflectionAmount = 1.0;
  79745. _this.reflectionReflectance0 = 0.05;
  79746. _this.reflectionReflectance90 = 0.5;
  79747. _this.useRGBColor = true;
  79748. _this.enableNoise = false;
  79749. /**
  79750. * Number of Simultaneous lights allowed on the material.
  79751. */
  79752. _this._maxSimultaneousLights = 4;
  79753. _this.maxSimultaneousLights = 4;
  79754. /**
  79755. * Keep track of the image processing observer to allow dispose and replace.
  79756. */
  79757. _this._imageProcessingObserver = null;
  79758. // Temp values kept as cache in the material.
  79759. _this._renderTargets = new BABYLON.SmartArray(16);
  79760. _this._reflectionControls = BABYLON.Vector4.Zero();
  79761. // Setup the default processing configuration to the scene.
  79762. _this._attachImageProcessingConfiguration(null);
  79763. _this.getRenderTargetTextures = function () {
  79764. _this._renderTargets.reset();
  79765. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  79766. _this._renderTargets.push(_this._diffuseTexture);
  79767. }
  79768. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  79769. _this._renderTargets.push(_this._reflectionTexture);
  79770. }
  79771. return _this._renderTargets;
  79772. };
  79773. return _this;
  79774. }
  79775. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  79776. /**
  79777. * Sets the reflection reflectance fresnel values according to the default standard
  79778. * empirically know to work well :-)
  79779. */
  79780. set: function (value) {
  79781. var reflectionWeight = value;
  79782. if (reflectionWeight < 0.5) {
  79783. reflectionWeight = reflectionWeight * 2.0;
  79784. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 * reflectionWeight;
  79785. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 * reflectionWeight;
  79786. }
  79787. else {
  79788. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  79789. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 + (1.0 - BackgroundMaterial.standardReflectance0) * reflectionWeight;
  79790. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 + (1.0 - BackgroundMaterial.standardReflectance90) * reflectionWeight;
  79791. }
  79792. },
  79793. enumerable: true,
  79794. configurable: true
  79795. });
  79796. /**
  79797. * Attaches a new image processing configuration to the PBR Material.
  79798. * @param configuration (if null the scene configuration will be use)
  79799. */
  79800. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  79801. var _this = this;
  79802. if (configuration === this._imageProcessingConfiguration) {
  79803. return;
  79804. }
  79805. // Detaches observer.
  79806. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  79807. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  79808. }
  79809. // Pick the scene configuration if needed.
  79810. if (!configuration) {
  79811. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  79812. }
  79813. else {
  79814. this._imageProcessingConfiguration = configuration;
  79815. }
  79816. // Attaches observer.
  79817. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  79818. _this._markAllSubMeshesAsImageProcessingDirty();
  79819. });
  79820. };
  79821. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  79822. /**
  79823. * Gets the image processing configuration used either in this material.
  79824. */
  79825. get: function () {
  79826. return this._imageProcessingConfiguration;
  79827. },
  79828. /**
  79829. * Sets the Default image processing configuration used either in the this material.
  79830. *
  79831. * If sets to null, the scene one is in use.
  79832. */
  79833. set: function (value) {
  79834. this._attachImageProcessingConfiguration(value);
  79835. // Ensure the effect will be rebuilt.
  79836. this._markAllSubMeshesAsTexturesDirty();
  79837. },
  79838. enumerable: true,
  79839. configurable: true
  79840. });
  79841. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  79842. /**
  79843. * Gets wether the color curves effect is enabled.
  79844. */
  79845. get: function () {
  79846. return this.imageProcessingConfiguration.colorCurvesEnabled;
  79847. },
  79848. /**
  79849. * Sets wether the color curves effect is enabled.
  79850. */
  79851. set: function (value) {
  79852. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  79853. },
  79854. enumerable: true,
  79855. configurable: true
  79856. });
  79857. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  79858. /**
  79859. * Gets wether the color grading effect is enabled.
  79860. */
  79861. get: function () {
  79862. return this.imageProcessingConfiguration.colorGradingEnabled;
  79863. },
  79864. /**
  79865. * Gets wether the color grading effect is enabled.
  79866. */
  79867. set: function (value) {
  79868. this.imageProcessingConfiguration.colorGradingEnabled = value;
  79869. },
  79870. enumerable: true,
  79871. configurable: true
  79872. });
  79873. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  79874. /**
  79875. * Gets wether tonemapping is enabled or not.
  79876. */
  79877. get: function () {
  79878. return this._imageProcessingConfiguration.toneMappingEnabled;
  79879. },
  79880. /**
  79881. * Sets wether tonemapping is enabled or not
  79882. */
  79883. set: function (value) {
  79884. this._imageProcessingConfiguration.toneMappingEnabled = value;
  79885. },
  79886. enumerable: true,
  79887. configurable: true
  79888. });
  79889. ;
  79890. ;
  79891. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  79892. /**
  79893. * The camera exposure used on this material.
  79894. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  79895. * This corresponds to a photographic exposure.
  79896. */
  79897. get: function () {
  79898. return this._imageProcessingConfiguration.exposure;
  79899. },
  79900. /**
  79901. * The camera exposure used on this material.
  79902. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  79903. * This corresponds to a photographic exposure.
  79904. */
  79905. set: function (value) {
  79906. this._imageProcessingConfiguration.exposure = value;
  79907. },
  79908. enumerable: true,
  79909. configurable: true
  79910. });
  79911. ;
  79912. ;
  79913. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  79914. /**
  79915. * Gets The camera contrast used on this material.
  79916. */
  79917. get: function () {
  79918. return this._imageProcessingConfiguration.contrast;
  79919. },
  79920. /**
  79921. * Sets The camera contrast used on this material.
  79922. */
  79923. set: function (value) {
  79924. this._imageProcessingConfiguration.contrast = value;
  79925. },
  79926. enumerable: true,
  79927. configurable: true
  79928. });
  79929. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  79930. /**
  79931. * Gets the Color Grading 2D Lookup Texture.
  79932. */
  79933. get: function () {
  79934. return this._imageProcessingConfiguration.colorGradingTexture;
  79935. },
  79936. /**
  79937. * Sets the Color Grading 2D Lookup Texture.
  79938. */
  79939. set: function (value) {
  79940. this.imageProcessingConfiguration.colorGradingTexture = value;
  79941. },
  79942. enumerable: true,
  79943. configurable: true
  79944. });
  79945. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  79946. /**
  79947. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  79948. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  79949. * 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;
  79950. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  79951. */
  79952. get: function () {
  79953. return this.imageProcessingConfiguration.colorCurves;
  79954. },
  79955. /**
  79956. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  79957. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  79958. * 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;
  79959. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  79960. */
  79961. set: function (value) {
  79962. this.imageProcessingConfiguration.colorCurves = value;
  79963. },
  79964. enumerable: true,
  79965. configurable: true
  79966. });
  79967. /**
  79968. * The entire material has been created in order to prevent overdraw.
  79969. * @returns false
  79970. */
  79971. BackgroundMaterial.prototype.needAlphaTesting = function () {
  79972. return true;
  79973. };
  79974. /**
  79975. * The entire material has been created in order to prevent overdraw.
  79976. * @returns true if blending is enable
  79977. */
  79978. BackgroundMaterial.prototype.needAlphaBlending = function () {
  79979. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  79980. };
  79981. /**
  79982. * Checks wether the material is ready to be rendered for a given mesh.
  79983. * @param mesh The mesh to render
  79984. * @param subMesh The submesh to check against
  79985. * @param useInstances Specify wether or not the material is used with instances
  79986. */
  79987. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  79988. var _this = this;
  79989. if (useInstances === void 0) { useInstances = false; }
  79990. if (subMesh.effect && this.isFrozen) {
  79991. if (this._wasPreviouslyReady) {
  79992. return true;
  79993. }
  79994. }
  79995. if (!subMesh._materialDefines) {
  79996. subMesh._materialDefines = new BackgroundMaterialDefines();
  79997. }
  79998. var scene = this.getScene();
  79999. var defines = subMesh._materialDefines;
  80000. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  80001. if (defines._renderId === scene.getRenderId()) {
  80002. return true;
  80003. }
  80004. }
  80005. var engine = scene.getEngine();
  80006. // Lights
  80007. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  80008. defines._needNormals = true;
  80009. // Textures
  80010. if (defines._areTexturesDirty) {
  80011. defines._needUVs = false;
  80012. if (scene.texturesEnabled) {
  80013. if (scene.getEngine().getCaps().textureLOD) {
  80014. defines.TEXTURELODSUPPORT = true;
  80015. }
  80016. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  80017. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  80018. return false;
  80019. }
  80020. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  80021. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  80022. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  80023. defines.OPACITYFRESNEL = this._opacityFresnel;
  80024. }
  80025. else {
  80026. defines.DIFFUSE = false;
  80027. defines.DIFFUSEHASALPHA = false;
  80028. defines.GAMMADIFFUSE = false;
  80029. defines.OPACITYFRESNEL = false;
  80030. }
  80031. var reflectionTexture = this._reflectionTexture;
  80032. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  80033. if (!reflectionTexture.isReadyOrNotBlocking()) {
  80034. return false;
  80035. }
  80036. defines.REFLECTION = true;
  80037. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  80038. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  80039. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  80040. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  80041. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  80042. defines.INVERTCUBICMAP = true;
  80043. }
  80044. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  80045. switch (reflectionTexture.coordinatesMode) {
  80046. case BABYLON.Texture.CUBIC_MODE:
  80047. case BABYLON.Texture.INVCUBIC_MODE:
  80048. defines.REFLECTIONMAP_CUBIC = true;
  80049. break;
  80050. case BABYLON.Texture.EXPLICIT_MODE:
  80051. defines.REFLECTIONMAP_EXPLICIT = true;
  80052. break;
  80053. case BABYLON.Texture.PLANAR_MODE:
  80054. defines.REFLECTIONMAP_PLANAR = true;
  80055. break;
  80056. case BABYLON.Texture.PROJECTION_MODE:
  80057. defines.REFLECTIONMAP_PROJECTION = true;
  80058. break;
  80059. case BABYLON.Texture.SKYBOX_MODE:
  80060. defines.REFLECTIONMAP_SKYBOX = true;
  80061. break;
  80062. case BABYLON.Texture.SPHERICAL_MODE:
  80063. defines.REFLECTIONMAP_SPHERICAL = true;
  80064. break;
  80065. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  80066. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  80067. break;
  80068. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  80069. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  80070. break;
  80071. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  80072. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  80073. break;
  80074. }
  80075. if (this.reflectionFresnel) {
  80076. defines.REFLECTIONFRESNEL = true;
  80077. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  80078. this._reflectionControls.x = this.reflectionAmount;
  80079. this._reflectionControls.y = this.reflectionReflectance0;
  80080. this._reflectionControls.z = this.reflectionReflectance90;
  80081. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  80082. }
  80083. else {
  80084. defines.REFLECTIONFRESNEL = false;
  80085. defines.REFLECTIONFALLOFF = false;
  80086. }
  80087. }
  80088. else {
  80089. defines.REFLECTION = false;
  80090. defines.REFLECTIONFALLOFF = false;
  80091. defines.REFLECTIONBLUR = false;
  80092. defines.REFLECTIONMAP_3D = false;
  80093. defines.REFLECTIONMAP_SPHERICAL = false;
  80094. defines.REFLECTIONMAP_PLANAR = false;
  80095. defines.REFLECTIONMAP_CUBIC = false;
  80096. defines.REFLECTIONMAP_PROJECTION = false;
  80097. defines.REFLECTIONMAP_SKYBOX = false;
  80098. defines.REFLECTIONMAP_EXPLICIT = false;
  80099. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  80100. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  80101. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  80102. defines.INVERTCUBICMAP = false;
  80103. defines.REFLECTIONMAP_OPPOSITEZ = false;
  80104. defines.LODINREFLECTIONALPHA = false;
  80105. defines.GAMMAREFLECTION = false;
  80106. }
  80107. }
  80108. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  80109. defines.USERGBCOLOR = this._useRGBColor;
  80110. defines.NOISE = this._enableNoise;
  80111. }
  80112. if (defines._areImageProcessingDirty) {
  80113. if (!this._imageProcessingConfiguration.isReady()) {
  80114. return false;
  80115. }
  80116. this._imageProcessingConfiguration.prepareDefines(defines);
  80117. }
  80118. // Misc.
  80119. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, defines);
  80120. // Values that need to be evaluated on every frame
  80121. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, false);
  80122. // Attribs
  80123. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  80124. if (mesh) {
  80125. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  80126. mesh.createNormals(true);
  80127. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  80128. }
  80129. }
  80130. }
  80131. // Get correct effect
  80132. if (defines.isDirty) {
  80133. defines.markAsProcessed();
  80134. scene.resetCachedMaterial();
  80135. // Fallbacks
  80136. var fallbacks = new BABYLON.EffectFallbacks();
  80137. if (defines.FOG) {
  80138. fallbacks.addFallback(0, "FOG");
  80139. }
  80140. if (defines.POINTSIZE) {
  80141. fallbacks.addFallback(1, "POINTSIZE");
  80142. }
  80143. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  80144. if (defines.NUM_BONE_INFLUENCERS > 0) {
  80145. fallbacks.addCPUSkinningFallback(0, mesh);
  80146. }
  80147. //Attributes
  80148. var attribs = [BABYLON.VertexBuffer.PositionKind];
  80149. if (defines.NORMAL) {
  80150. attribs.push(BABYLON.VertexBuffer.NormalKind);
  80151. }
  80152. if (defines.UV1) {
  80153. attribs.push(BABYLON.VertexBuffer.UVKind);
  80154. }
  80155. if (defines.UV2) {
  80156. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  80157. }
  80158. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  80159. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  80160. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  80161. "vFogInfos", "vFogColor", "pointSize",
  80162. "vClipPlane", "mBones",
  80163. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  80164. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos",
  80165. "shadowLevel", "alpha",
  80166. "vBackgroundCenter", "vReflectionControl",
  80167. "vDiffuseInfos", "diffuseMatrix",
  80168. ];
  80169. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  80170. var uniformBuffers = ["Material", "Scene"];
  80171. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  80172. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  80173. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  80174. uniformsNames: uniforms,
  80175. uniformBuffersNames: uniformBuffers,
  80176. samplers: samplers,
  80177. defines: defines,
  80178. maxSimultaneousLights: this._maxSimultaneousLights
  80179. });
  80180. var onCompiled = function (effect) {
  80181. if (_this.onCompiled) {
  80182. _this.onCompiled(effect);
  80183. }
  80184. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  80185. };
  80186. var join = defines.toString();
  80187. subMesh.setEffect(scene.getEngine().createEffect("background", {
  80188. attributes: attribs,
  80189. uniformsNames: uniforms,
  80190. uniformBuffersNames: uniformBuffers,
  80191. samplers: samplers,
  80192. defines: join,
  80193. fallbacks: fallbacks,
  80194. onCompiled: onCompiled,
  80195. onError: this.onError,
  80196. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  80197. }, engine), defines);
  80198. this.buildUniformLayout();
  80199. }
  80200. if (!subMesh.effect || !subMesh.effect.isReady()) {
  80201. return false;
  80202. }
  80203. defines._renderId = scene.getRenderId();
  80204. this._wasPreviouslyReady = true;
  80205. return true;
  80206. };
  80207. /**
  80208. * Build the uniform buffer used in the material.
  80209. */
  80210. BackgroundMaterial.prototype.buildUniformLayout = function () {
  80211. // Order is important !
  80212. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  80213. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  80214. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  80215. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  80216. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  80217. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  80218. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  80219. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  80220. this._uniformBuffer.addUniform("pointSize", 1);
  80221. this._uniformBuffer.addUniform("shadowLevel", 1);
  80222. this._uniformBuffer.addUniform("alpha", 1);
  80223. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  80224. this._uniformBuffer.addUniform("vReflectionControl", 4);
  80225. this._uniformBuffer.create();
  80226. };
  80227. /**
  80228. * Unbind the material.
  80229. */
  80230. BackgroundMaterial.prototype.unbind = function () {
  80231. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  80232. this._uniformBuffer.setTexture("diffuseSampler", null);
  80233. }
  80234. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  80235. this._uniformBuffer.setTexture("reflectionSampler", null);
  80236. }
  80237. _super.prototype.unbind.call(this);
  80238. };
  80239. /**
  80240. * Bind only the world matrix to the material.
  80241. * @param world The world matrix to bind.
  80242. */
  80243. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  80244. this._activeEffect.setMatrix("world", world);
  80245. };
  80246. /**
  80247. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  80248. * @param world The world matrix to bind.
  80249. * @param subMesh The submesh to bind for.
  80250. */
  80251. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  80252. var scene = this.getScene();
  80253. var defines = subMesh._materialDefines;
  80254. if (!defines) {
  80255. return;
  80256. }
  80257. var effect = subMesh.effect;
  80258. if (!effect) {
  80259. return;
  80260. }
  80261. this._activeEffect = effect;
  80262. // Matrices
  80263. this.bindOnlyWorldMatrix(world);
  80264. // Bones
  80265. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  80266. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  80267. if (mustRebind) {
  80268. this._uniformBuffer.bindToEffect(effect, "Material");
  80269. this.bindViewProjection(effect);
  80270. var reflectionTexture = this._reflectionTexture;
  80271. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  80272. // Texture uniforms
  80273. if (scene.texturesEnabled) {
  80274. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  80275. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  80276. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  80277. }
  80278. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  80279. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  80280. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  80281. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  80282. }
  80283. }
  80284. if (this.shadowLevel > 0) {
  80285. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  80286. }
  80287. this._uniformBuffer.updateFloat("alpha", this.alpha);
  80288. // Point size
  80289. if (this.pointsCloud) {
  80290. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  80291. }
  80292. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  80293. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  80294. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  80295. }
  80296. // Textures
  80297. if (scene.texturesEnabled) {
  80298. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  80299. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  80300. }
  80301. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  80302. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  80303. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  80304. }
  80305. else if (!defines.REFLECTIONBLUR) {
  80306. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  80307. }
  80308. else {
  80309. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  80310. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  80311. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  80312. }
  80313. if (defines.REFLECTIONFRESNEL) {
  80314. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  80315. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  80316. }
  80317. }
  80318. }
  80319. // Clip plane
  80320. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  80321. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  80322. }
  80323. if (mustRebind || !this.isFrozen) {
  80324. if (scene.lightsEnabled) {
  80325. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  80326. }
  80327. // View
  80328. this.bindView(effect);
  80329. // Fog
  80330. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  80331. // image processing
  80332. this._imageProcessingConfiguration.bind(this._activeEffect);
  80333. }
  80334. this._uniformBuffer.update();
  80335. this._afterBind(mesh);
  80336. };
  80337. /**
  80338. * Dispose the material.
  80339. * @forceDisposeEffect Force disposal of the associated effect.
  80340. * @forceDisposeTextures Force disposal of the associated textures.
  80341. */
  80342. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  80343. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  80344. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  80345. if (forceDisposeTextures) {
  80346. if (this.diffuseTexture) {
  80347. this.diffuseTexture.dispose();
  80348. }
  80349. if (this.reflectionTexture) {
  80350. this.reflectionTexture.dispose();
  80351. }
  80352. }
  80353. this._renderTargets.dispose();
  80354. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  80355. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  80356. }
  80357. _super.prototype.dispose.call(this, forceDisposeEffect);
  80358. };
  80359. /**
  80360. * Clones the material.
  80361. * @name The cloned name.
  80362. * @returns The cloned material.
  80363. */
  80364. BackgroundMaterial.prototype.clone = function (name) {
  80365. var _this = this;
  80366. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  80367. };
  80368. /**
  80369. * Serializes the current material to its JSON representation.
  80370. * @returns The JSON representation.
  80371. */
  80372. BackgroundMaterial.prototype.serialize = function () {
  80373. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  80374. serializationObject.customType = "BABYLON.BackgroundMaterial";
  80375. return serializationObject;
  80376. };
  80377. /**
  80378. * Gets the class name of the material
  80379. * @returns "BackgroundMaterial"
  80380. */
  80381. BackgroundMaterial.prototype.getClassName = function () {
  80382. return "BackgroundMaterial";
  80383. };
  80384. /**
  80385. * Parse a JSON input to create back a background material.
  80386. * @param source
  80387. * @param scene
  80388. * @param rootUrl
  80389. * @returns the instantiated BackgroundMaterial.
  80390. */
  80391. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  80392. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  80393. };
  80394. /**
  80395. * Standard reflectance value at parallel view angle.
  80396. */
  80397. BackgroundMaterial.standardReflectance0 = 0.05;
  80398. /**
  80399. * Standard reflectance value at grazing angle.
  80400. */
  80401. BackgroundMaterial.standardReflectance90 = 0.5;
  80402. __decorate([
  80403. BABYLON.serializeAsColor3()
  80404. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  80405. __decorate([
  80406. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  80407. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  80408. __decorate([
  80409. BABYLON.serialize()
  80410. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  80411. __decorate([
  80412. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  80413. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  80414. __decorate([
  80415. BABYLON.serializeAsColor3()
  80416. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  80417. __decorate([
  80418. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  80419. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  80420. __decorate([
  80421. BABYLON.serialize()
  80422. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  80423. __decorate([
  80424. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  80425. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  80426. __decorate([
  80427. BABYLON.serializeAsColor3()
  80428. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  80429. __decorate([
  80430. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  80431. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  80432. __decorate([
  80433. BABYLON.serialize()
  80434. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  80435. __decorate([
  80436. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  80437. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  80438. __decorate([
  80439. BABYLON.serializeAsTexture()
  80440. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  80441. __decorate([
  80442. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80443. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  80444. __decorate([
  80445. BABYLON.serialize()
  80446. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  80447. __decorate([
  80448. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80449. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  80450. __decorate([
  80451. BABYLON.serializeAsTexture()
  80452. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  80453. __decorate([
  80454. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80455. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  80456. __decorate([
  80457. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80458. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  80459. __decorate([
  80460. BABYLON.serialize()
  80461. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  80462. __decorate([
  80463. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80464. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  80465. __decorate([
  80466. BABYLON.serialize()
  80467. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  80468. __decorate([
  80469. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80470. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  80471. __decorate([
  80472. BABYLON.serializeAsVector3()
  80473. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  80474. __decorate([
  80475. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80476. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  80477. __decorate([
  80478. BABYLON.serialize()
  80479. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  80480. __decorate([
  80481. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80482. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  80483. __decorate([
  80484. BABYLON.serialize()
  80485. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  80486. __decorate([
  80487. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80488. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  80489. __decorate([
  80490. BABYLON.serialize()
  80491. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  80492. __decorate([
  80493. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80494. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  80495. __decorate([
  80496. BABYLON.serialize()
  80497. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  80498. __decorate([
  80499. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80500. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  80501. __decorate([
  80502. BABYLON.serialize()
  80503. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  80504. __decorate([
  80505. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80506. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  80507. __decorate([
  80508. BABYLON.serialize()
  80509. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  80510. __decorate([
  80511. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80512. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  80513. __decorate([
  80514. BABYLON.serialize()
  80515. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  80516. __decorate([
  80517. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80518. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  80519. __decorate([
  80520. BABYLON.serialize()
  80521. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  80522. __decorate([
  80523. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80524. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  80525. __decorate([
  80526. BABYLON.serialize()
  80527. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  80528. __decorate([
  80529. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80530. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  80531. __decorate([
  80532. BABYLON.serializeAsImageProcessingConfiguration()
  80533. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  80534. return BackgroundMaterial;
  80535. }(BABYLON.PushMaterial));
  80536. BABYLON.BackgroundMaterial = BackgroundMaterial;
  80537. })(BABYLON || (BABYLON = {}));
  80538. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  80539. var __assign = (this && this.__assign) || Object.assign || function(t) {
  80540. for (var s, i = 1, n = arguments.length; i < n; i++) {
  80541. s = arguments[i];
  80542. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  80543. t[p] = s[p];
  80544. }
  80545. return t;
  80546. };
  80547. var BABYLON;
  80548. (function (BABYLON) {
  80549. /**
  80550. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  80551. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  80552. * It also helps with the default setup of your imageProcessing configuration.
  80553. */
  80554. var EnvironmentHelper = /** @class */ (function () {
  80555. /**
  80556. * constructor
  80557. * @param options
  80558. * @param scene The scene to add the material to
  80559. */
  80560. function EnvironmentHelper(options, scene) {
  80561. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  80562. this._scene = scene;
  80563. this._setupBackground();
  80564. this._setupImageProcessing();
  80565. }
  80566. /**
  80567. * Creates the default options for the helper.
  80568. */
  80569. EnvironmentHelper._getDefaultOptions = function () {
  80570. return {
  80571. createGround: true,
  80572. groundSize: 15,
  80573. groundTexture: this._groundTextureCDNUrl,
  80574. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  80575. groundOpacity: 0.9,
  80576. enableGroundShadow: true,
  80577. groundShadowLevel: 0.5,
  80578. enableGroundMirror: false,
  80579. groundMirrorSizeRatio: 0.3,
  80580. groundMirrorBlurKernel: 64,
  80581. groundMirrorAmount: 1,
  80582. groundMirrorFresnelWeight: 1,
  80583. groundMirrorFallOffDistance: 0,
  80584. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  80585. groundYBias: 0.00001,
  80586. createSkybox: true,
  80587. skyboxSize: 20,
  80588. skyboxTexture: this._skyboxTextureCDNUrl,
  80589. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  80590. backgroundYRotation: 0,
  80591. sizeAuto: true,
  80592. rootPosition: BABYLON.Vector3.Zero(),
  80593. setupImageProcessing: true,
  80594. environmentTexture: this._environmentTextureCDNUrl,
  80595. cameraExposure: 0.8,
  80596. cameraContrast: 1.2,
  80597. toneMappingEnabled: true,
  80598. };
  80599. };
  80600. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  80601. /**
  80602. * Gets the root mesh created by the helper.
  80603. */
  80604. get: function () {
  80605. return this._rootMesh;
  80606. },
  80607. enumerable: true,
  80608. configurable: true
  80609. });
  80610. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  80611. /**
  80612. * Gets the skybox created by the helper.
  80613. */
  80614. get: function () {
  80615. return this._skybox;
  80616. },
  80617. enumerable: true,
  80618. configurable: true
  80619. });
  80620. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  80621. /**
  80622. * Gets the skybox texture created by the helper.
  80623. */
  80624. get: function () {
  80625. return this._skyboxTexture;
  80626. },
  80627. enumerable: true,
  80628. configurable: true
  80629. });
  80630. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  80631. /**
  80632. * Gets the skybox material created by the helper.
  80633. */
  80634. get: function () {
  80635. return this._skyboxMaterial;
  80636. },
  80637. enumerable: true,
  80638. configurable: true
  80639. });
  80640. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  80641. /**
  80642. * Gets the ground mesh created by the helper.
  80643. */
  80644. get: function () {
  80645. return this._ground;
  80646. },
  80647. enumerable: true,
  80648. configurable: true
  80649. });
  80650. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  80651. /**
  80652. * Gets the ground texture created by the helper.
  80653. */
  80654. get: function () {
  80655. return this._groundTexture;
  80656. },
  80657. enumerable: true,
  80658. configurable: true
  80659. });
  80660. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  80661. /**
  80662. * Gets the ground mirror created by the helper.
  80663. */
  80664. get: function () {
  80665. return this._groundMirror;
  80666. },
  80667. enumerable: true,
  80668. configurable: true
  80669. });
  80670. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  80671. /**
  80672. * Gets the ground mirror render list to helps pushing the meshes
  80673. * you wish in the ground reflection.
  80674. */
  80675. get: function () {
  80676. if (this._groundMirror) {
  80677. return this._groundMirror.renderList;
  80678. }
  80679. return null;
  80680. },
  80681. enumerable: true,
  80682. configurable: true
  80683. });
  80684. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  80685. /**
  80686. * Gets the ground material created by the helper.
  80687. */
  80688. get: function () {
  80689. return this._groundMaterial;
  80690. },
  80691. enumerable: true,
  80692. configurable: true
  80693. });
  80694. /**
  80695. * Updates the background according to the new options
  80696. * @param options
  80697. */
  80698. EnvironmentHelper.prototype.updateOptions = function (options) {
  80699. var newOptions = __assign({}, this._options, options);
  80700. if (this._ground && !newOptions.createGround) {
  80701. this._ground.dispose();
  80702. this._ground = null;
  80703. }
  80704. if (this._groundMaterial && !newOptions.createGround) {
  80705. this._groundMaterial.dispose();
  80706. this._groundMaterial = null;
  80707. }
  80708. if (this._groundTexture) {
  80709. if (this._options.groundTexture != newOptions.groundTexture) {
  80710. this._groundTexture.dispose();
  80711. this._groundTexture = null;
  80712. }
  80713. }
  80714. if (this._skybox && !newOptions.createSkybox) {
  80715. this._skybox.dispose();
  80716. this._skybox = null;
  80717. }
  80718. if (this._skyboxMaterial && !newOptions.createSkybox) {
  80719. this._skyboxMaterial.dispose();
  80720. this._skyboxMaterial = null;
  80721. }
  80722. if (this._skyboxTexture) {
  80723. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  80724. this._skyboxTexture.dispose();
  80725. this._skyboxTexture = null;
  80726. }
  80727. }
  80728. if (this._groundMirror && !newOptions.enableGroundMirror) {
  80729. this._groundMirror.dispose();
  80730. this._groundMirror = null;
  80731. }
  80732. if (this._scene.environmentTexture) {
  80733. if (this._options.environmentTexture != newOptions.environmentTexture) {
  80734. this._scene.environmentTexture.dispose();
  80735. }
  80736. }
  80737. this._options = newOptions;
  80738. this._setupBackground();
  80739. this._setupImageProcessing();
  80740. };
  80741. /**
  80742. * Sets the primary color of all the available elements.
  80743. * @param color
  80744. */
  80745. EnvironmentHelper.prototype.setMainColor = function (color) {
  80746. if (this.groundMaterial) {
  80747. this.groundMaterial.primaryColor = color;
  80748. }
  80749. if (this.skyboxMaterial) {
  80750. this.skyboxMaterial.primaryColor = color;
  80751. }
  80752. if (this.groundMirror) {
  80753. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  80754. }
  80755. };
  80756. /**
  80757. * Setup the image processing according to the specified options.
  80758. */
  80759. EnvironmentHelper.prototype._setupImageProcessing = function () {
  80760. if (this._options.setupImageProcessing) {
  80761. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  80762. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  80763. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  80764. this._setupEnvironmentTexture();
  80765. }
  80766. };
  80767. /**
  80768. * Setup the environment texture according to the specified options.
  80769. */
  80770. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  80771. if (this._scene.environmentTexture) {
  80772. return;
  80773. }
  80774. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  80775. this._scene.environmentTexture = this._options.environmentTexture;
  80776. return;
  80777. }
  80778. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  80779. this._scene.environmentTexture = environmentTexture;
  80780. };
  80781. /**
  80782. * Setup the background according to the specified options.
  80783. */
  80784. EnvironmentHelper.prototype._setupBackground = function () {
  80785. if (!this._rootMesh) {
  80786. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  80787. }
  80788. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  80789. var sceneSize = this._getSceneSize();
  80790. if (this._options.createGround) {
  80791. this._setupGround(sceneSize);
  80792. this._setupGroundMaterial();
  80793. this._setupGroundDiffuseTexture();
  80794. if (this._options.enableGroundMirror) {
  80795. this._setupGroundMirrorTexture(sceneSize);
  80796. }
  80797. this._setupMirrorInGroundMaterial();
  80798. }
  80799. if (this._options.createSkybox) {
  80800. this._setupSkybox(sceneSize);
  80801. this._setupSkyboxMaterial();
  80802. this._setupSkyboxReflectionTexture();
  80803. }
  80804. this._rootMesh.position.x = sceneSize.rootPosition.x;
  80805. this._rootMesh.position.z = sceneSize.rootPosition.z;
  80806. this._rootMesh.position.y = sceneSize.rootPosition.y;
  80807. };
  80808. /**
  80809. * Get the scene sizes according to the setup.
  80810. */
  80811. EnvironmentHelper.prototype._getSceneSize = function () {
  80812. var groundSize = this._options.groundSize;
  80813. var skyboxSize = this._options.skyboxSize;
  80814. var rootPosition = this._options.rootPosition;
  80815. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  80816. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  80817. }
  80818. var sceneExtends = this._scene.getWorldExtends();
  80819. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  80820. if (this._options.sizeAuto) {
  80821. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  80822. this._scene.activeCamera.upperRadiusLimit) {
  80823. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  80824. skyboxSize = groundSize;
  80825. }
  80826. var sceneDiagonalLenght = sceneDiagonal.length();
  80827. if (sceneDiagonalLenght > groundSize) {
  80828. groundSize = sceneDiagonalLenght * 2;
  80829. skyboxSize = groundSize;
  80830. }
  80831. // 10 % bigger.
  80832. groundSize *= 1.1;
  80833. skyboxSize *= 1.5;
  80834. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  80835. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  80836. }
  80837. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  80838. };
  80839. /**
  80840. * Setup the ground according to the specified options.
  80841. */
  80842. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  80843. var _this = this;
  80844. if (!this._ground) {
  80845. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  80846. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  80847. this._ground.parent = this._rootMesh;
  80848. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  80849. }
  80850. this._ground.receiveShadows = this._options.enableGroundShadow;
  80851. };
  80852. /**
  80853. * Setup the ground material according to the specified options.
  80854. */
  80855. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  80856. if (!this._groundMaterial) {
  80857. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  80858. }
  80859. this._groundMaterial.alpha = this._options.groundOpacity;
  80860. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  80861. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  80862. this._groundMaterial.primaryLevel = 1;
  80863. this._groundMaterial.primaryColor = this._options.groundColor;
  80864. this._groundMaterial.secondaryLevel = 0;
  80865. this._groundMaterial.tertiaryLevel = 0;
  80866. this._groundMaterial.useRGBColor = false;
  80867. this._groundMaterial.enableNoise = true;
  80868. if (this._ground) {
  80869. this._ground.material = this._groundMaterial;
  80870. }
  80871. };
  80872. /**
  80873. * Setup the ground diffuse texture according to the specified options.
  80874. */
  80875. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  80876. if (!this._groundMaterial) {
  80877. return;
  80878. }
  80879. if (this._groundTexture) {
  80880. return;
  80881. }
  80882. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  80883. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  80884. return;
  80885. }
  80886. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  80887. diffuseTexture.gammaSpace = false;
  80888. diffuseTexture.hasAlpha = true;
  80889. this._groundMaterial.diffuseTexture = diffuseTexture;
  80890. };
  80891. /**
  80892. * Setup the ground mirror texture according to the specified options.
  80893. */
  80894. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  80895. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80896. if (!this._groundMirror) {
  80897. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  80898. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  80899. this._groundMirror.anisotropicFilteringLevel = 1;
  80900. this._groundMirror.wrapU = wrapping;
  80901. this._groundMirror.wrapV = wrapping;
  80902. this._groundMirror.gammaSpace = false;
  80903. if (this._groundMirror.renderList) {
  80904. for (var i = 0; i < this._scene.meshes.length; i++) {
  80905. var mesh = this._scene.meshes[i];
  80906. if (mesh !== this._ground &&
  80907. mesh !== this._skybox &&
  80908. mesh !== this._rootMesh) {
  80909. this._groundMirror.renderList.push(mesh);
  80910. }
  80911. }
  80912. }
  80913. }
  80914. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  80915. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  80916. };
  80917. /**
  80918. * Setup the ground to receive the mirror texture.
  80919. */
  80920. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  80921. if (this._groundMaterial) {
  80922. this._groundMaterial.reflectionTexture = this._groundMirror;
  80923. this._groundMaterial.reflectionFresnel = true;
  80924. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  80925. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  80926. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  80927. }
  80928. };
  80929. /**
  80930. * Setup the skybox according to the specified options.
  80931. */
  80932. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  80933. var _this = this;
  80934. if (!this._skybox) {
  80935. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  80936. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  80937. }
  80938. this._skybox.parent = this._rootMesh;
  80939. };
  80940. /**
  80941. * Setup the skybox material according to the specified options.
  80942. */
  80943. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  80944. if (!this._skybox) {
  80945. return;
  80946. }
  80947. if (!this._skyboxMaterial) {
  80948. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  80949. }
  80950. this._skyboxMaterial.useRGBColor = false;
  80951. this._skyboxMaterial.primaryLevel = 1;
  80952. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  80953. this._skyboxMaterial.secondaryLevel = 0;
  80954. this._skyboxMaterial.tertiaryLevel = 0;
  80955. this._skyboxMaterial.enableNoise = true;
  80956. this._skybox.material = this._skyboxMaterial;
  80957. };
  80958. /**
  80959. * Setup the skybox reflection texture according to the specified options.
  80960. */
  80961. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  80962. if (!this._skyboxMaterial) {
  80963. return;
  80964. }
  80965. if (this._skyboxTexture) {
  80966. return;
  80967. }
  80968. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  80969. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  80970. return;
  80971. }
  80972. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  80973. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  80974. this._skyboxTexture.gammaSpace = false;
  80975. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  80976. };
  80977. /**
  80978. * Dispose all the elements created by the Helper.
  80979. */
  80980. EnvironmentHelper.prototype.dispose = function () {
  80981. if (this._groundMaterial) {
  80982. this._groundMaterial.dispose(true, true);
  80983. }
  80984. if (this._skyboxMaterial) {
  80985. this._skyboxMaterial.dispose(true, true);
  80986. }
  80987. this._rootMesh.dispose(false);
  80988. };
  80989. /**
  80990. * Default ground texture URL.
  80991. */
  80992. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  80993. /**
  80994. * Default skybox texture URL.
  80995. */
  80996. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  80997. /**
  80998. * Default environment texture URL.
  80999. */
  81000. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  81001. return EnvironmentHelper;
  81002. }());
  81003. BABYLON.EnvironmentHelper = EnvironmentHelper;
  81004. })(BABYLON || (BABYLON = {}));
  81005. //# sourceMappingURL=babylon.environmentHelper.js.map
  81006. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\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 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>\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#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}","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\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>\nvoid main(void) {\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\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\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#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\ngl_FragColor=color;\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=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}","gpuRenderParticlesVertexShader":"#version 300 es\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 velocity;\nvoid main() {\ngl_PointSize=1.0;\ngl_Position=vec4(position,1.0);\n}","gpuRenderParticlesPixelShader":"void main() {\ngl_FragColor=vec4(1.0);\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\nuniform float timeDelta;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 velocity;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec3 outVelocity;\nvoid main() {\nif (age>=life) {\n\noutPosition=vec3(0,0,0);\n\noutAge=0.0;\noutLife=life;\n\noutVelocity=vec3(0,1,0);\n} else {\noutPosition=position+velocity*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutVelocity=velocity;\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#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=abs(texture2D(textureSampler,vUV).r);\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,1.0);\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=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}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","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#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 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}","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);\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\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\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\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#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\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\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}"};
  81007. 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#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}\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 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#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;\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":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(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=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\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\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\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\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#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#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 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 PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*KERNEL_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*KERNEL_WEIGHT{X};\n#endif","kernelBlurFragment2":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*KERNEL_DEP_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*KERNEL_DEP_WEIGHT{X};\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;\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 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};"};
  81008. (function universalModuleDefinition(root, factory) {
  81009. var f = factory();
  81010. if (root && root["BABYLON"]) {
  81011. return;
  81012. }
  81013. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  81014. globalObject["BABYLON"] = f;
  81015. if(typeof exports === 'object' && typeof module === 'object')
  81016. module.exports = f;
  81017. else if(typeof define === 'function' && define.amd)
  81018. define(["BABYLON"], factory);
  81019. else if(typeof exports === 'object')
  81020. exports["BABYLON"] = f;
  81021. else {
  81022. root["BABYLON"] = f;
  81023. }
  81024. })(this, function() {
  81025. return BABYLON;
  81026. });